REST API in Python: First steps with FastAPI

Dilmer Gonzalez – Sr. Backend Engineer

What is Fast API?

According to the official site, FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

FastAPI was released in 2018, and it was created by Sebastián Ramírez. At some point, he saw that we’d need a framework that could take advantage of the new language features that were not available before (Python 3.6+ type hints) and combining them with the existing OpenAPI standards and also making it faster than other existing frameworks like Django and Flask, so this is when FastAPI was born.

Currently, many big tech companies like Uber, Netflix, and Microsoft are using FastAPI to build their apps.

Key Features
  • Fast: Very high performance, on par with Node.js and Go, thanks to libraries like Starlette (for the web part) and Pydantic (for the data part).
  • Fast to code: Increase the speed of developing features between 200% and 300%.*
  • Fewer bugs: Reduce about 40% of human induced errors.* 
  • Intuitive: Great editor support, completion everywhere and less debugging time.
  • Easy: Designed to be easy to use and learn. Also, less time reading docs.
  • Short: Minimize code duplication. Multiple features from each parameter declaration.
  • Robust: Get production-ready code with automatic interactive documentation.
  • Standards-based: Fully compatible with open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.

*Estimation based on tests on an internal development team, building production applications.

FastAPI vs Flask vs Django

Flask

Flask is a Python microframework that includes caching, ORM and authentication. It’s considered to be scalable, easy to use and fast. This framework is mostly used to build applications for E-commerce systems, social media, network sites, etc.

Pros Cons
It’s flexible, you can manipulate lots of parts of this framework Any data type can be passed, no data validation
Intuitive, so it’s great for beginners due to its simplicity Single source that handles requests in turns, so the response time can take longer
Perfect for unit testing due to its built-in development server

Django

Django is a Python framework for web development and was created using the Model-Template-View pattern. This framework is mostly used to build applications for high load booking engines, shopping platforms, school management systems, CRM systems, IOS and Android applications supporting web-based applications, etc.

Pros Cons
Code structure is very efficient, making it easy to add more functionalities Older versions may not be compatible with the newest ones, making it slow to update the applications in some cases
DRF (Django Rest Framework) is a flexible toolkit to build web APIs in Django Django models can have no mixins, they just have simple inheritance
Easy to build web APIs with Django because of its modular and customizable architecture Uses ORM, which was created before SQLAlchemy, making Django ORM inferior to SQLAlchemy because it is less flexible
Security emphasis by providing defense against SQL Injection and Cross Site Request Forgery (CSRF) attacks

FastAPI

Pros Cons
The data is validated even in nested JSON requests FastAPI uses Pydantic for request validation, so it sometimes requires you to create custom validators because it’s not always very intuitive
Easy to do Exception Handling Since this framework is still really new, the community is smaller in comparison to other frameworks
Supports async code using the async/await Python keywords
Creating a basic service with FastAPI

We’ll start by creating a simple Hello World! application and then we’ll explain the code.

In order to start coding this, I recommend you to install and set up a virtual environment of your choice (using Python 3.6+) to isolate the libraries that we need here and do not affect what you already have in your machine.

Once you have the virtual environment up and running, you can make sure that the Python version you’re using is compatible with FastAPI, so we can run python –version and the output should be a version greater than 3.6.

Installing the basic dependencies

In your virtual environment, run pip install fastapi to install the last FastAPI dependency that we have available.

Now, we need an ASGI server to run the application, so we can use either Uvicorn or Hypercorn. For this example, we’ll use Uvicorn, so you can run pip install “uvicorn[standard]” in order to install it in your virtual environment.

Creating the main file

Now, you can create a new file using an IDE of your choice and name it as main.py, in which you can put the following content (lines 17-27 are comments to explain what the code does, so they’re optional to add):

Running the server

Since we’re using Uvicorn in this example, you can start the server by running uvicorn main:app –reload

Let’s break this down:

  • main: refers to the file name
  • app: refers to the object of FastAPI created inside the main.py file
  • –reload: parameter that makes the server restart automatically after the code changes
Checking it

Open your browser at http://127.0.0.1:8000/items/5?q=query1

You now see the JSON response like:

{“item_id”: 5, “q”: “query1”}

Interactive API docs

Now go to http://127.0.0.1:8000/docs and then, you’ll see the automatic interactive API documentation (provided by swagger UI):

Alternative API docs

Now, go to http://127.0.0.1:8000/redoc and then, you’ll see the alternative automatic documentation (provided by ReDoc):

Example Upgrade

Please modify the main.py file to receive a body from a PUT request and declare this body using standard Python types, thanks to Pydantic.

The server should reload automatically (because you added –reload to the uvicorn command above).

Interactive API docs upgrade

Now go to http://127.0.0.1:8000/docs and then, you’ll see that the interactive API documentation will be automatically updated, including the new body:

Now, click on the button “Try it out” and it will allow you to fill the parameters and directly interact with the API:

Then, click on the button “Execute” and now the user interface will communicate with your API, send the parameters, get the results and show them on the screen:

Alternative API docs upgrade

Now, go to http://127.0.0.1:8000/redoc and then, you’ll see that the alternative documentation will be also updated to reflect the new query parameters and the body:

Recap

  • With FastAPI, you declare once the types of parameters, body, etc. as function parameters, using standard modern Python types.
  • You don’t have to learn new syntax, methods or classes from a specific library, you can use the same standard structures of Python 3.6+.
  • In the above example, the data is validated and, in case of invalid inputs according to the types defined, the software will show clear errors. These validations will occur even in nested JSON structures.
  • FastAPI provides automatic and interactive API documentation, including 2 user interfaces: Swagger UI and ReDoc.
References

 

Share on facebook
Share on twitter
Share on linkedin

Do You Want To Boost Your Business?

Drop us a line and keep in touch.

How Mismo Works

Jobs

About

Resources