Python Friday #214: First Steps With FastAPI

There are many projects in Python that we can use to create an API. After exploring a few options, I decided to go with FastAPI and explore it over the next few weeks. FastAPI is not only fast when it comes to serving requests, but also when it comes to writing code for it. Let us explore the many features we can use while we create our API.

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

 

Installation

The main speed advantage of FastAPI comes from the asynchronous processing of requests. Therefore, we not only need to install FastAPI itself, but we also need to install an ASGI server to use its asynchronous features:

 

A minimalistic API

For our first steps we can use the minimalistic example from the FastAPI documentation:

The code reminds me a lot of Flask, except for the async keyword and the type hints. While we do not need the async keyword for those specific methods, I like to have them consistent with the rest of the application. As we add more functionality over the next weeks, we will see where we can benefit from asynchronous processing.

 

Run the API

We can run our API inside uvicorn with this command:

INFO: Will watch for changes in these directories: [‘C:\\FastAPI\\quickstart’]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [48200] using WatchFiles
INFO: Started server process [62140]
INFO: Waiting for application startup.
INFO: Application startup complete.

Our application (the app variable in the main.py file) is now running on port 8000 and will reload if we change a file. When we open the URL in the browser, we should see this output:

Our browser shows us the Hello World as JSON.

 

Explore the documentation

If we open the URL http://127.0.0.1:8000/docs we see one of the magical parts of FastAPI in action. Without any code written by us we get the Swagger documentation for all our endpoints:

We get an interactive documentation for our API that allows us to run the code against the real API.

We can explore our API through the web browser and download the OpenAPI secification for our API – all without extra work from us.

 

Next

With our minimalistic API we already have a lot in place: There are our specified endpoints, an asynchronous-capable server and the OpenAPI specification that documents our API. Next week we explore the async keyword that we put in front of the method definitions.

5 thoughts on “Python Friday #214: First Steps With FastAPI”

Leave a Comment

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