FastAPI: High-Performance Python Web Framework

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed for building APIs quickly with automatic data validation, serialization, and interactive documentation.

FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts. It is one of the fastest Python frameworks available, making it ideal for building high-performance applications and microservices.

FastAPI is particularly well-suited for building RESTful APIs and microservices, and it has gained popularity for its ease of use, performance, and automatic generation of OpenAPI documentation.

Traditional web frameworks like Flask and Django are great, but FastAPI takes advantage of Python's type hints to provide automatic request validation, serialization, and documentation generation. This leads to fewer bugs and faster development times.

Why was FastAPI invented?

FastAPI was created by Sebastián Ramírez in 2018 to address the need for a modern web framework that could leverage Python's type hints for automatic data validation and serialization, while also providing high performance and ease of use.

The goal was to create a framework that would allow developers to build APIs quickly and efficiently, with automatic generation of OpenAPI documentation and interactive API docs.

FastAPI is designed to be easy to use, with a focus on developer productivity and performance. It has gained popularity for its simplicity, speed, and the ability to create robust APIs with minimal boilerplate code.

Is FastAPI opensource?

Yes, FastAPI is an open-source web framework released under the MIT License. This means that it is free to use, modify, and distribute, making it accessible to developers worldwide.

Where does FastAPI fit in the Python web development lifestyle?

FastAPI fits into the Python web development lifestyle as a modern alternative to traditional frameworks like Flask and Django. It is particularly well-suited for building APIs and microservices, leveraging Python's type hints for automatic data validation and serialization.

Disadvantages of FastAPI

Official FastAPI link

You can find the official FastAPI documentation and resources at FastAPI Documentation.

FastAPI vs Flask vs Django

In summary, choose FastAPI for high-performance APIs, Flask for lightweight and flexible projects, and Django for full-stack web applications.

Key Features of FastAPI

FastAPI Installation

pip install fastapi[all]

The [all] option installs FastAPI along with recommended dependencies such as uvicorn (an ASGI server) for running your application.

Where does FastAPI fit in an overall web-app architecture?

FastAPI fits into the web application architecture as a backend framework for building APIs and microservices. It can serve as the interface between the frontend (e.g., React, Vue.js) and the database or other services. FastAPI handles HTTP requests, processes data, and communicates with databases or external services, providing a robust and efficient backend solution.

Can we use FastAPI in combination with flask or Django?

Yes, you can use FastAPI in combination with Flask or Django. FastAPI can serve as a microservice within a larger application, allowing you to leverage its performance and features while still using Flask or Django for other parts of your application. This approach allows you to take advantage of FastAPI's strengths, such as automatic data validation and asynchronous programming, while maintaining the existing functionality of Flask or Django.

What are Microservices?

Microservices are an architectural style that structures an application as a collection of small, loosely coupled services. Each service is designed to perform a specific business function and can be developed, deployed, and scaled independently. This approach allows for greater flexibility, scalability, and maintainability compared to monolithic architectures.

FastAPI is particularly well-suited for building microservices due to its high performance, automatic data validation, and support for asynchronous programming. It allows developers to create lightweight, efficient services that can communicate with each other over HTTP or other protocols.

Microservices can be written in different programming languages and can communicate with each other using APIs, message queues, or other communication protocols. This allows teams to choose the best tools for each service while maintaining a cohesive application architecture.

FastAPI's features, such as automatic OpenAPI documentation generation and dependency injection, make it an excellent choice for building microservices that are easy to develop, test, and maintain.

What is Rest API?

REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server communication model and uses standard HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources. RESTful APIs are designed to be simple, scalable, and stateless, making them easy to use and maintain.

Text Flowchart of a web app architecture that includes fastapi in it



User (Browser or Mobile App)
    |
    v
Frontend (e.g., React, Vue, Angular, Flutter)
    |
    |  ⬅️ Sends HTTP/HTTPS requests (REST, GraphQL, WebSockets)
    v
API Layer (FastAPI / Flask / Django)
    |
    |  ⬅️ Routes requests, handles auth, validates inputs
    v
Business Logic / Service Layer
    |
    |  ⬅️ Contains core logic, processes requests, controls access
    v
Database Layer (PostgreSQL, MySQL, SQLite, etc.)
    |
    |  ⬅️ ORM used here (SQLAlchemy, Django ORM, Tortoise, etc.)
    v
External Services (payment gateways, ML APIs, etc.)

Optional Enhancements
---------------------
Caching Layer (Redis, Memcached) ⬅️ Improves read performance
    |
    v
Message Broker (Kafka, RabbitMQ)
    |
    v
Background Workers (Celery, RQ, Dramatiq)
    |
    v
Async Tasks (e.g., email, data processing, ML tasks)

Monitoring / Logging (Prometheus, Grafana, ELK, Sentry)
    ⬅️ Observability, performance, and error tracking

Deployment (Docker, Kubernetes, Cloud: AWS, Azure, GCP)
    ⬅️ Infrastructure setup, container orchestration

Load Balancer (Nginx, HAProxy)
    ⬅️ Distributes traffic, SSL termination, caching

CDN (Cloudflare, AWS CloudFront)
    ⬅️ Serves static assets closer to the user

    

To run FastAPI

To run a FastAPI application as shown in the examples, you typically use an ASGI server like Uvicorn. Here's how to run a FastAPI based python app:



    import uvicorn
    from fastapi import FastAPI
    app = FastAPI()
    
    if __name__ == "__main__":
      uvicorn.run(app, host="localhost", port=8000, log_level="info")
    

Paste the above code in the file where you have defined your FastAPI app. By running this code, you start the FastAPI application on localhost at port 8000. The log_level can be set to "info", "debug", or other levels as needed.

After running this command, you can access your FastAPI application at http://localhost:8000. FastAPI also provides interactive API documentation at /docs and /redoc.

9 Practical FastAPI Examples

1. Basic endpoint


  from fastapi import FastAPI

  app = FastAPI()

  @app.get("/")
  def read_root():
    return {"message": "Hello, FastAPI"}
    

2. Path parameter


  from fastapi import Path

  @app.get("/items/{item_id}")
  def read_item(item_id: int = Path(..., description="The ID of the item to get")):
    return {"item_id": item_id}
    

3. Query parameters


  from typing import Optional
  from fastapi import Query

  @app.get("/search/")
  def search(q: Optional[str] = Query(None, max_length=50)):
    return {"query": q}
    

4. Request body with Pydantic model


  from pydantic import BaseModel
  from typing import Optional

  class Item(BaseModel):
    name: str
    price: float
    is_offer: Optional[bool] = None

  @app.post("/items/")
  def create_item(item: Item):
    return {"item": item}
    

5. Async endpoint


  @app.get("/async/")
  async def async_endpoint():
    return {"message": "This is async"}
    

6. Using default values


  @app.get("/defaults/")
  def defaults(limit: int = 10, offset: int = 0):
    return {"limit": limit, "offset": offset}
    

7. Multiple request methods


  @app.api_route("/multi-method/", methods=["GET", "POST"])
  def multi_method():
    return {"message": "Supports GET and POST"}
    

8. Dependency Injection example


  from typing import Optional
  from fastapi import Depends

  def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 10):
    return {"q": q, "skip": skip, "limit": limit}

  @app.get("/dependency/")
  def read_dependency(commons: dict = Depends(common_parameters)):
    return commons
    

9. Custom response status code


  from fastapi import status

  @app.post("/items-with-status/", status_code=status.HTTP_201_CREATED)
  def create_item_with_status(item: Item):
    return item