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
0:05 because it's not in the right format or something's missing,
0:08 some of that is actually handled already by FastAPI.
0:12 So for example, if X is passed over and the X is a
0:16 string that can be converted to an integer,
0:18 FastAPI will just handle that. It will return a JSON response with a dictionary that
0:23 has some details about the error message.
0:25 But there's other times where just certain values are required.
0:28 Like, for example, you have to have a non-zero Z if Z is
0:33 specified in this calculation because you'll get a divide by zero.
0:37 So in this case, we got Z from the user, and it's zero,
0:40 so we need to tell them "no,
0:41 no, no, this is bad".
0:42 If we just try to do the division,
0:44 it's going to crash our server, they'll
0:45 get a 500 response, still think our service is unreliable when really they sent us
0:50 bad data, so we want to communicate that back. We're going to create some kind of
0:53 error dictionary not shown here that we're gonna return like error is the message,
0:58 you know, Z has to be non-zero for division and so on.
1:02 We're going to do that as a FastAPI JSON response.
1:06 We're going to set the status code to 400 or whatever status code you think is
1:09 the best fit and then the content to a dictionary,
1:12 which will be converted to JSON, and sent back along with the status code,
1:16 and that's it. Super easy to return errors in this controlled way back to the clients.