loading...
Cover image for Quickly Develop Highly Performant APIs with FastAPI & Python

Quickly Develop Highly Performant APIs with FastAPI & Python

livecodestream profile image Juan Cruz Martinez Originally published at livecodestream.dev on ・4 min read

If you have read some of my previous posts on Python, you know I’m a Flask fan, and it is my goto for building APIs in Python. However, recently I started to hear a lot about a new API framework for Python called FastAPI, and after building some APIs with it I can say, it is amazing!

This project was created by Sebastian Ramírez and it has accumulated at the time of writing almost 20k stars, and big names building APIs in production like Microsoft, Uber, Netflix, and others.

But why is this new library so popular and how does it compare with Flask or Django?


Features

FastAPI is a rather minimalistic framework, more of the likes of Flask. However, that doesn’t make it less powerful. FastAPI is built using modern Python concepts and it’s based out of Python 3.6 type declarations. Let’s see some of the features this library is packed with:

Automatic Docs

A must-have for any API is documentation about the endpoints and the types. A common approach to solve this problem is the use of OpenAPI and subsequently tools like Swagger UI or ReDoc to present the information. These come packed automatically with FastAPI. Allowing you to focus more on your code rather than setting up tools.

Typed Python

This is a BIG one. FastAPI makes use of Python 3.6 type declarations (thanks to Pydantic), this means that it uses a Python feature that allows you to specify the type of a variable. And this framework makes extensive use out of it, providing you with great editor support. Autocompletion works amazingly.

Here is a sample code using typed declarations:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/")
def read_root(item: Item):
    return item.price

We just went from

name

to

name: str

that’s it! and as a result

Autocompletion in FastAPI using PyCharm

Beautiful!

Validation

Validation is already integrated into this framework thanks to Pydantic. You can validate standard Python types as well as some custom field validations. Here are a few examples:

  • JSON objects (dict)
  • JSON array (list)
  • String (str) with min and max lengths
  • Numbers (int, float) with min and max values
  • URL
  • Email
  • UUID
  • and many more…

Security and authentication

This is a crucial part of any API, and it’s code that we usually just repeat, so why not integrate much of it into the framework? FastAPI does exactly that.

The library provides support for the followings:

  • HTTP Basic
  • OAuth2 (JWT tokens)
  • API keys in headers, query params, or cookies.

Documentation

Perhaps is not exactly a feature of the framework, however, it is worth mentioning. The documentation of the project is simply amazing. It’s very clear and covers the topics with examples and explanations.


Performance

FastAPI is fast! but not only fast to code, but also it processes requests super fast! And is not me just saying it. You can check the benchmarks across multiple frameworks using the techempower benchmark tool. Here are the results I got for Python frameworks. Flask and Django are way behind in the list, with FastAPI being first and thus the most performant.

TechEmpower Benchmark Result


Asynchronous by nature

Let’s take a look at the following code:

@app.post("/item/", response_model=Item)
async def create_item(item: Item):
    result = await some_code_running_in_background(item)
    return result

Is that Javascript? I promise you, is not, though looks familiar, right? That snippet is actually Python, using async methods.

FastAPI supports asynchronous endpoints by default, which can simplify and make your code more efficient. This is a huge advantage over Flask. Django on the other hand already made some async support work, but is not as integrated as it is in FastAPI.


Conclusion

FastAPI is a relatively new framework that follows the minimalist approach of Flask but adding crucial features that makes it easier to work with and with a stunning performance. It is a great choice for your next API project, and you will read me talking more about it as I use it more and more on my APIs.

Thanks for reading!


If you like the story, please don't forget to subscribe to our free newsletter so we can stay connected: https://livecodestream.dev/subscribe

Posted on by:

livecodestream profile

Juan Cruz Martinez

@livecodestream

I'm an entrepreneur, developer, author, speaker, and doer of things. Email List: https://livecodestream.dev/subscribe

Discussion

markdown guide