
FastAPI: A High-Performance Python Framework for Rapid Web Development
Published Wed May 01 2024
Introduction
FastAPI is a modern and high-performance Python web framework designed specifically for building APIs and web applications quickly and efficiently. Developed by Sebastián Ramírez and first released in 2018, FastAPI has rapidly gained traction in the developer community thanks to its focus on providing key features for API and web app development with excellent performance.
FastAPI is built on top of Starlette and Pydantic, both of which contribute to its ease of use and performance. Starlette provides a lightweight and fast ASGI framework foundation, while Pydantic enables data validation using Python type hints.
Compared to well-established frameworks like Django and Flask, FastAPI differentiates itself by emphasizing developer velocity, productivity, and maintainable code.
In this post, we’ll look at FastAPI’s key features, compare it to alternatives like Django and Flask, and provide use cases where FastAPI shines. We’ll also share hands-on impressions of using the framework and offer suggestions on when FastAPI may be the right choice for your next project.
FastAPI Features and Benefits
FastAPI provides several features that make it well-suited for web development, especially APIs:
Automatic Data Validation
FastAPI leverages Pydantic and Python type hints to automatically validate data. This reduces boilerplate code and ensures that the API's inputs and outputs match the expected schemas.
For example:
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
joined: date
@app.post("/users")
async def create_user(user: User):
# user will be validated against the User model
return user
Here, FastAPI automatically validates that the user object received matches the User model containing the expected types for id, name, and joined.
Automatic Interactive API Documentation
FastAPI integrates with Swagger UI and ReDoc to automatically generate interactive documentation for the API. This lets you quickly test endpoints and review parameters without additional work.

FastAPI Swagger UI interactive documentation
Modern Python Features
FastAPI takes advantage of modern Python features like type hints and asynchronous programming. This results in cleaner and more idiomatic code while improving performance.
For example, FastAPI supports Python's async/await syntax:
@app.get("/items/{item_id}")
async def read_item(item_id: int):
results = await async_database_call(item_id)
return results
Developer Friendly
FastAPI aims to provide a pleasant developer experience. It has an intuitive interface, helpful error messages, and encourages best practices that lead to maintainable code.
For example, clear and explicit error messages help identify issues faster:
422 Unprocessable Entity
body validation error
field required (type=value_error.missing)
> body
> item_id
field required (type=value_error.missing)
ASGI
ASGI, which stands for Asynchronous Server Gateway Interface, is a specification between web servers and Python web applications or frameworks to allow greater concurrency. It's a successor to WSGI, the Web Server Gateway Interface, which has been the standard for synchronous Python web applications.
ASGI supports both synchronous and asynchronous communication, making it suitable for handling a large number of simultaneous incoming requests, particularly those that might spend a lot of time waiting, such as requests involving I/O operations.
FastAPI vs Other Frameworks
How does FastAPI compare to popular frameworks like Django and Flask? Let's take a look at some of the key differences.
FastAPI vs Django
Django is a mature, full-featured framework with extensive documentation and an active community. However, it has a larger footprint and steeper learning curve than FastAPI.
For example, Django's more complex project structure can make initial setup take longer, as well as requiring a deeper understanding of the framework's internals:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
app/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
Whereas FastAPI can utilize a much simpler directory structure:
myapi/
main.py
models.py
schemas.py
api/
__init__.py
endpoints.py
Django's built-in ORM and admin interface are advantages for some projects. However, FastAPI's focus on API development makes it better suited for building lightweight, high-performance services. Django has a lot of features built-in that aren't needed in many applications. Django tries to give you everything a website COULD need, but that can be overkill for smaller projects or applications that require high performance, because you often don't NEED everything Django provides.
FastAPI vs Flask
Flask and FastAPI are more directly comparable compared to Django and FastAPI, as they are both microframeworks that don't have a lot of included bloat. Compared to Flask, FastAPI's built-in features make it easier to get started and maintain code. While Flask and FastAPI are both well-suited for building APIs, and both are similar in speed, with Flask being slightly faster, FastAPI's automatic data validation and documentation generation make it a better choice for API development, in my opinion. With Flask, validation and documentation generation requires extra libraries and boilerplate code.
For example, validating a POST request in Flask:
from flask import request
from werkzeug.exceptions import BadRequest
@app.route("/users", methods=["POST"])
def create_user():
data = request.get_json()
if not data:
return BadRequest("No JSON provided")
if "name" not in data:
return BadRequest("Missing name")
if not isinstance(data["name"], str):
return BadRequest("Name must be a string")
if "age" not in data:
return BadRequest("Missing age")
if not isinstance(data["age"], int):
return BadRequest("Age must be an integer")
# ... etc for each field to be validated
# ... Create the user ...
return user
The same validation in FastAPI:
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
# ...etc
@app.post("/users")
async def create_user(user: User):
# All input data is validated against the User model automatically, returning a 422 error if validation fails
# ... Create the user ...
return user
FastAPI also allows for validating the output data, like so:
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
# ...etc
class UserOut(BaseModel):
name: str
age: int
# ...etc
@app.post("/users", response_model=UserOut)
async def create_user(user: User):
# All input data is validated against the User model automatically, returning a 422 error if validation fails
# ... Create the user ...
return user
In this example, the response_model parameter validates the output User object against the UserOut model, returning a 422 error if validation fails. This ensures that the output data matches the expected format, and also assists in generating more detailed documentation.
API Documentation in Flask
Generating comprehensive API documentation in Flask requires installing extensions, configuring swagger, and decorating routes:
from flask import Flask
from flask_swagger_ui import get_swaggerui_blueprint
from flasgger import Swagger, swag_from
app = Flask(__name__)
### Required Swagger setup ###
SWAGGER_URL = '/api/docs'
API_URL = '/static/swagger.json'
SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={
'app_name': "My App"
}
)
app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
### End Swagger setup ###
@app.route('/users', methods=['GET'])
@swag_from('swagger/users.yml')
def get_users():
"""Gets list of users.
---
get:
description: Returns list of users
responses:
200:
description: Successful response
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string
"""
pass
if __name__ == "__main__":
app.run()
The Swagger spec must be explicitly configured and flask-swagger-ui registered to serve docs. API routes require decorators to define schema and parameters. This is a lot of overhead to keep documentation in sync.
API Documentation in FastAPI
FastAPI automatically generates OpenAPI schemas and Swagger UI interactive documentation:
from fastapi import FastAPI
app = FastAPI()
class UserOut(BaseModel):
id: int
name: str
@app.get("/users", response_model=list[UserOut])
async def get_users():
return [{"id": 1, "name": "John"}]
if __name__ == "__main__":
import uvicorn
uvicorn.run(app)
That's it! FastAPI parses the function signatures and return types to build a live Swagger UI. Documentation always stays up-to-date with the code. The developer experience is greatly improved compared to manually defining schemas in Flask.
First Impressions of FastAPI
After building an initial API with FastAPI, here are some thoughts:
Quick Setup
FastAPI was extremely quick to install and start using. The ability to use it directly without an application factory or settings file accelerated development.
Intuitive Syntax
The syntax for creating endpoints, validating parameters, and configuring docs made sense right away. Python type hints integrate directly for validation.
Automatic Documentation
Generating interactive API docs using Swagger UI required no extra configuration. It was easy to immediately test endpoints and review parameters.
Pydantic Data Validation
Leveraging Pydantic for data validation using Python type hints reduced boilerplate code tremendously. Input and output was validated automatically.
Performance
In benchmarks, FastAPI achieved a score of 1184 compared to Django's 274, and Flask's 1229. This makes it a strong choice for high-performance web applications that don't require the speed of a lower-level language like Go or Rust, like typical APIs and microservices.
Balance of Flexibility and Structure
While slightly opinionated in some areas like project structure, FastAPI still provided freedom to organize code beyond the basics as needed.
Positive First Impressions
After creating several APIs with FastAPI, I'm impressed with FastAPI's performance, automatic validation, docs generation, and overall developer experience. The community and ecosystem are growing rapidly as well.
When to Use FastAPI
Based on its strengths and comparisons to alternatives, here are some good use cases for FastAPI:
- APIs and Microservices: FastAPI is purpose-built for API development. Its performance and dev experience make it great for microservices too.
- Real-time Applications: FastAPI's ASGI support makes it a strong choice for apps requiring low latency like live streaming, gaming, and messaging.
- Machine Learning: For ML applications processing lots of data, FastAPI provides speed and reliability.
- Legacy Modernization: You can use FastAPI to create a modern API frontend for legacy systems and improve performance.
- Prototyping and MVPs: FastAPI's ability to create APIs and docs quickly accelerates prototyping and building minimal viable products.
Real-World Usage
Several companies and organizations have adopted FastAPI for their projects, demonstrating its effectiveness and versatility in real-world use cases. Some examples include:
- Uber: Uber uses FastAPI in their internal projects to build and maintain high-performance APIs. FastAPI's performance and ease of use make it a suitable choice for Uber's large-scale applications that need to handle a high volume of requests efficiently. Uber uses FastAPI in their Ludwig machine learning framework, a deep learning toolbox.
- Netflix: Netflix uses FastAPI for some of their backend services. FastAPI's performance and support for asynchronous programming help Netflix build services that are capable of handling large amounts of data and concurrent connections. Netflix uses FastAPI for their open-source crisis management orchestration framework, Dispatch.
- Microsoft: Microsoft utilizes FastAPI in some of their internal projects, taking advantage of its performance, data validation, and automatic documentation generation capabilities. FastAPI's features help Microsoft's development teams build APIs and services that are efficient, robust, and easily maintainable. Some machine learning related services that are made with FastAPI are being integrated into core Windows and Office products.
- Art & Logic: At Art+Logic, I have started utilizing FastAPI for various projects, including new applications and supporting older applications.
In one particular project, we were working with a legacy application built on WebSauna, a Pyramid-based framework. The existing system relied on server-side rendering for its pages, which posed a challenge when developing a native iOS application, as we needed to create API endpoints for it. We were faced with two choices: either expand the existing WebSauna application by adding RESTful API endpoints or implement an API sidecar using another framework.
Given that WebSauna is a legacy framework with little to no documentation and no active support, extending it would have been a difficult and time-consuming process. Moreover, it is much heavier and harder to extend compared to FastAPI. Considering these factors, we decided to go with FastAPI for its lightweight nature and ease of use.
With FastAPI, we were able to quickly develop the necessary API for the iOS developer to utilize, streamlining the development process and ensuring a more efficient and maintainable solution, using a modern framework. This will also allow for the client to opt into creating new clients for web and Android, as having an API gives them that option.
These real-world use cases demonstrate FastAPI's capabilities in handling a variety of projects across different industries. FastAPI's performance, ease of use, and data validation features make it an attractive choice for companies and organizations looking to build efficient, reliable, and high-performance web applications and APIs.
Key Takeaways
Here are some of the key highlights of FastAPI as a Python web framework:
- Excellent performance thanks to optimizations like ASGI support
- Automatic data validation using Pydantic and type hints
- Streamlined API development experience
- Automatic interactive documentation using OpenAPI schemas
- Rapidly growing ecosystem of plugins, extensions, and community support
FastAPI is ideal for developers who prioritize building APIs and web services with high productivity and little boilerplate code. Its balance of ease-of-use, flexibility, performance, and reliability make it a worthy contender among Python's web frameworks.
As FastAPI continues maturing, it will be exciting to see the additional capabilities it develops alongside the growing community support. Based on my experience so far, I believe FastAPI can be the right choice for many API and web app projects that need speed, validation, and great documentation.