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, that was JSON, with a status code,
0:07 however FastAPI actually has some shortcut ways to improve upon this. So if we could go over here and say "fastapi.responses", when you
0:16 look in here, notice we have a JSON response, a file response, an HTML response, plain text, redirect, etcetera, etcetera, etcetera. So that's cool.
0:24 Let's go into the JSON one which is up here. And how is this different? Well, it's gonna automatically set this to the media types,
0:32 so we don't have to specify that. And also, the content is going to be set to be not a string which would parse this JSON, but some kind of dictionary.
0:42 Just a straight dictionary there. And then the status code, well, we're still gonna need to set that,
0:47 because that's kind of error condition, like that. Okay, so let's wrap that so you all can read it.
0:53 They should do exactly the same thing as we had before. We go over here and
0:57 we refresh, everything is good. But now if we make it error out, notice again we get some JSON passed back here and if we look at the type,
1:08 it's application JSON. So same basic idea but we just have to write a little less code. We don't have to set the content type and all those things.
1:15 Also, if this content you wanted to pass back had come from some other location
1:20 or included other data, you'd have to use the JSON Library to turn into a string, which should be a hassle,
1:25 So this is much better. If you're gonna return a JSON response, do it like this.

Talk Python's Mastodon Michael Kennedy's Mastodon