Modern APIs with FastAPI and Python Transcripts
Chapter: Building our first API
Lecture: Using specialized responses

Login or purchase this course to watch this video and the rest of the course contents.
0:00 We saw we could create a response and return it with some content,
0:03 that was JSON, with a status code,
0:06 however FastAPI actually has some shortcut ways to improve upon this.
0:11 So if we could go over here and say "fastapi.responses", when you
0:15 look in here, notice we have a JSON response,
0:17 a file response, an html response, plain text, redirect,
0:21 etcetera, etcetera, etcetera. So that's cool.
0:23 Let's go into the JSON one which is up here.
0:27 And how is this different? Well,
0:28 it's gonna automatically set this to the media types,
0:31 so we don't have to specify that.
0:33 And also, the content is going to be set to be not a string which
0:39 would parse this JSON, but some kind of dictionary.
0:41 Just a straight dictionary there. And then the status code,
0:44 well, we're still gonna need to set that,
0:46 because that's kind of error condition, like that.
0:49 Okay, so let's wrap that so you all can read it.
0:52 They should do exactly the same thing as we had before. We go over here and
0:56 we refresh, everything is good. But now if we make it error out, notice again
1:01 we get some JSON passed back here and if we look at the type,
1:07 it's application JSON. So same basic idea
1:10 but we just have to write a little less code.
1:12 We don't have to set the content type and all those things.
1:14 Also, if this content you wanted to pass back had come from some other location
1:19 or included other data, you'd have to use the JSON Library to turn into a
1:22 string, which should be a hassle,
1:24 So this is much better. If you're gonna return a JSON response, do it like this.