Modern APIs with FastAPI and Python Transcripts
Chapter: Building our first API
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 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 will 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. Like, for example, you have to have a non-zero Z if Z is
0:34 specified in this calculation because you'll get a divide by zero. So in this case, we got Z from the user, and it's zero, so we need to tell them "no,
0:42 no, no, this is bad". If we just try to do the division, it's going to crash our server, they'll
0:46 get a 500 response, still think our service is unreliable when really they sent us
0:51 bad data, so we want to communicate that back. We're going to create some kind of
0:54 error dictionary not shown here that we're gonna return like error is the message, you know, Z has to be non-zero for division and so on.
1:03 We're going to do that as a FastAPI JSON response. We're going to set the status code to 400 or whatever status code you think is
1:10 the best fit and then the content to a dictionary, which will be converted to JSON, and sent back along with the status code,
1:17 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