#100DaysOfWeb in Python Transcripts
Chapter: Days 9-12: FastAPI
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
0:06
code. However, FastAPI actually has some shortcut ways to improve upon this. So if we can go over
0:12
here and say FastAPI.responses, and you look in here, notice we have a JSON response, a file
0:18
response, an HTML response, plain text, redirect, et cetera, et cetera, et cetera. 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 going to
0:29
automatically set this to the media type. So we don't have to specify that. And also the content
0:36
is going to be set to be a string, which would parse as JSON, but some kind of dictionary,
0:42
just a straight dictionary there. And then the status code, well, we're still going to need to
0:46
set that because that's kind of error condition like that. Okay, let's wrap that so you all can
0:52
read it. This should do exactly the same thing as we had before. Go over here and we refresh,
0:58
everything is good. But now if we make it error out, notice again, we get some JSON passed back
1:06
here. And if we look at the type, it's application JSON. So same basic idea, but we just have to
1:12
write a little less code. We don't have to set the content type and all those things. Also,
1:16
if this content you wanted to pass back had come from some other location or included other data,
1:21
you'd have to use the JSON library to turn into a string, which should be a hassle. So this is This is much better.
1:26
If you're going to return JSON response, do it like this.