FastAPI in python
Explore FastAPI’s powerful features, including async support, automatic validation, and built-in documentation, making it the go-to framework for modern Python APIs.

Overview
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.
The key features are:
Fast: Very high performance, on par with NodeJS and Go. One of the fastest Python frameworks available.
Fast to code: Increase the speed to develop features by about 200% to 300%.
Fewer bugs: Reduce about 40% of human (developer) induced errors.
Intuitive: Great editor support. Completion everywhere. Less time debugging.
Easy: Designed to be easy to use and learn. Less time reading docs.
Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
Robust: Get production-ready code. With automatic interactive documentation.
Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (Swagger) and JSON Schema.
Let’s dive in
Super fast to get started
FastAPI allows you to set up a fully functional API with just a few lines of code. For example, this is all you need to create a simple "Hello World" endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
Save it as main.py, run it with uvicorn main:app --reload, and voilà! You have a running API.
Built-in Validation
FastAPI uses Pydantic (really cool data validation library) to validate your data automatically. Just define your input schema, and it handles the rest. If someone sends invalid data, FastAPI will return a detailed error message explaining what's wrong. This is how easy it is to implement data validation
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
in_stock: bool
@app.post("/items/")
def create_item(item: Item):
return {"item": item}
Asynchronous by Design
FastAPI is built on top of Starlette, which means it fully supports asynchronous programming. This is great if your API interacts with databases, external APIs, or other time-consuming operations. This is unlike Flask, which another popular micro-service framework in python.
Asynchronous Endpoints
FastAPI’s support for asynchronous programming allows developers to handle multiple requests concurrently, leading to better performance in high-throughput applications. Unlike traditional synchronous frameworks, where each request is processed sequentially, async endpoints enable non-blocking operations using Python’s async
and await
keywords.
When to Use Async Endpoints
When dealing with I/O-bound operations such as database queries, external API calls, or file processing.
When handling a high number of concurrent users efficiently.
When integrating with modern async-based libraries like
httpx
(for HTTP requests) ordatabases
(for async database operations).
Interactive Documentation
One of FastAPI's coolest features is interactive documentation. Once your API is up, visit /docs or /redoc, and you'll find auto-generated, interactive docs based on your code. No extra effort needed!
Dependency Injection
Dependency Injection (DI) is a software design pattern that promotes modularity, reusability, and testability by allowing dependencies to be injected into functions or classes rather than being hardcoded. FastAPI has built-in support for dependency injection, making it a powerful feature for handling dependencies such as database connections, authentication mechanisms, and business logic.
How FastAPI Handles Dependency Injection
FastAPI’s DI system is declarative and built into the framework using Python’s type hinting. It enables developers to define dependencies separately and inject them into route handlers using Depends
. The dependency function is executed before the route function and its return value is passed as an argument.
Basic dependency injection
How it works:
common_dependency()
is a simple function that returns a string.The
Depends
function tells FastAPI that this dependency should be executed before handling the request.The result of
common_dependency()
is injected into the route function as thedata
parameter.
Advanced Dependency Injection
FastAPI allows injecting more complex dependencies like database sessions, authentication checks, and configuration settings.
Example: Database Connection as a Dependency
How it works:
The
get_db
function initializes a database session and ensures it is closed after use.yield
is used for cleanup after the dependency is executed.The
Depends(get_db)
injects the database session into the route.
Key differences with Flask
Flask and FastAPI are two of the most popular web frameworks in Python, but they have key differences in design philosophy, performance, and features.
I’ve summarized the key differences between the frameworks in the table below.
When to use one over the other
While both flask and fastapi are great frameworks, there are areas where one shines over the other. The table below summarizes this.
Final Verdict
Choose FastAPI if you need a high-performance, async-ready API with built-in documentation and validation.
Choose Flask if you're building a traditional web application with templating (like Jinja2) or if you prefer a lightweight framework with more flexibility.
The code for the examples shared for this post are available for free on my Github repository python-frameworks.
Conclusion
FastAPI is a game-changer for modern API development in Python. Its built-in validation, high performance, and async capabilities make it an excellent choice for both small and large-scale projects. If you’re looking for a framework that makes API development fast and enjoyable, FastAPI is worth exploring!
Happy coding!