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:
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:
1 2 |
# assert response.status_code == 200 assert response.status_code == 201 |
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:
1 2 3 4 5 |
@app.post("/api/todo") async def create_task(task: TaskInput): result = db.add(task) return JSONResponse(content=jsonable_encoder(result), status_code=status.HTTP_201_CREATED) |
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:
1 2 3 4 |
@app.delete("/api/todo/{id}") async def delete_task(id: int): db.delete(id) return Response(status_code=status.HTTP_204_NO_CONTENT) |
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”