#100DaysOfWeb in Python Transcripts
Chapter: Days 9-12: FastAPI
Lecture: Concept: Returning errors

Login or purchase this course to watch this video and the rest of the course contents.
0:00 If you've received some input, some data from the user that you just can't process because it's not in the right format or something's missing,
0:09 some of that is actually handled already by FastAPI. So for example, if an X is passed over and the X is a string that can be converted to an integer,
0:19 FastAPI will just handle that. It'll return a JSON response with a dictionary that has some details about the error message.
0:26 But there's other times where just certain values are required.
0:30 Like for example, you have to have a non-zero Z if a Z is specified in this calculation, because you'll get a divide by zero.
0:38 So in this case, we got Z from the user and it's zero, so we need to tell them, ""No, no, no, this is bad.
0:44 If we just try to do the division, it's going to crash our server.
0:46 They'll get a 500 response. They'll think our service is unreliable when really they sent us bad data. But we want to communicate that back.
0:53 We're going to create some kind of error dictionary not shown here that we're going to return like error is the message,
0:59 you know, Z has to be non-zero for division and so on. We're going to do that as a FastAPI JSON response.
1:07 We're going to set the status code to 400 or whatever status code you think is the best fit.
1:11 And then the content to a dictionary, which will be converted to JSON and sent back along with the status code.
1:18 And that's it. Super easy to return errors in this controlled way back to the clients.


Talk Python's Mastodon Michael Kennedy's Mastodon