Python Friday #224: Better HTTP Status Codes for FastAPI

Our to-do application currently responds with the HTTP status codes 200 when everything is ok and 404 if the requested task does not exist. While this works, it is not as specific as it could be. Let us explore our options when it comes to HTTP status codes.

This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.

 

What can we choose from?

There are many resources on the web that explain the different HTTP status codes. I like the site httpstatuses.com that has a useful overview and offers a lot of details when I need to know more:

The HTTP status codes with a quick summary of their meaning.

The detailed explanation of HTTP status code 201 for created entities.

 

Modify the status code for created tasks

The API currently returns the status code 200 when we create a task, but 201 (Created) would be a better fit. We can update the test to create a task and the prepare_task() method to expect a 201 instead of 200 status code:

In the API endpoint we create a JSONResponse object and encode our TaskOutput object explicitly to JSON. For the status_code we can write 201 or use the more explicit constant from fastapi.status:

If we omit the explicit JSON encoding, we get an error like this one:

TypeError: Object of type TaskOutput is not JSON serializable

 

Change the status code for deleted tasks

Another place where we can improve the status code is when we delete a task. Instead of 200 we can return 204 (no content). After changing the status code in the test, we can change the return value in our endpoint. Since we do not have data to send back, we use the Response class instead of JSONResponse:

 

Next

FastAPI allows us to use the appropriate status code for our response. That may look like an overhead, but it may be helpful for your clients when you do not send data back to use the status code 204 to make it explicit that there will be no content in the response.

While reading the documentation I noticed that I should return a header for the status code 201 that points to the location of the newly created task. Next week we figure out how we can set headers with FastAPI.

1 thought on “Python Friday #224: Better HTTP Status Codes for FastAPI”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.