Python Friday #246: Helpful Tricks for FastAPI

Before we end this series on FastAPI, I am going to take you for another round to show you a few helpful little tricks that can improve your FastAPI experience.

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

 

Add metadata to our API

We can add some additional information to our API to help our users. One of the most noticeable additions would be a title that shows up in the /docs endpoint. But we do not need to stop there. We can add a long description (that accepts Markdown), set a licence, offer contact information and much more:

If we restart our application, we see this addition to our documentation:

We now have a detailed description of our API right in the documentation.

 

Tags to group the endpoints

The more endpoints we have, the more entries we get in our OpenAPI documentation. If we want to group endpoints together, we can add tags to the endpoint or to the router:

If we restart our application, we see the documentation for our endpoints nicely grouped by our tags:

We can now find our tags and below a list of the endpoints we marked with that specific tag.

 

Metadata for our tags

We can add a small description to our tags with a metadata dictionary:

If we now reload our application, we find the description next to the tags and can even use links to access additional documentation:

We can see the description for the task tag and have a link to go to the blog series.

 

Set a port in Uvicorn

If you want to run two FastAPI applications at the same time, you get an error because the port is already in use. You can fix this problem with the --port parameter and set an explicit port:

 

Write a test when you explore a package

I strongly recommend you write a tiny little test when you try a package for FastAPI. That way you quickly notice how massive the package messes with the internals of FastAPI. It does not matter how well documented and maintained the package is, if you can no longer test your application, you have a problem.

I wanted to blog about a few more packages, but as soon as I wrote a test to check if they worked as expected, I could no longer run the test client for FastAPI. If you do not want to write any tests, you can ignore this trick – but be aware of what you are getting yourself into.

 

Conclusion

This series on FastAPI comes to an end. As with all topics, we could keep going on and add this feature or that package. But after exploring FastAPI for more than 7 months it is time for something new. I hope you enjoyed this journey as much as I did. The topics we covered gives us a good understanding of what can be done with FastAPI and how to do it.

Next week we leave FastAPI behind and fiddle with audio metadata.

Leave a Comment

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