// I need to

ModernizeUpgrade without breaking it RescueFix what someone else started Build NewTurn an idea into a product Reach More PeopleGet found, get used, include everyone

// Company

Case StudiesExpertiseAbout + CareersResourcesContact Book a call →
≡articleBuild New

FastAPI: A High-Performance Python Framework for Rapid Web Development

FastAPI is a modern and high-performance Python web framework designed specifically for building APIs and web applications quickly and efficiently.

Jagger Estep May 1, 20249 min read

FastAPI: A High-Performance Python Framework for Rapid Web Development

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.

Swagger UI docs example

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:

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:

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:

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.

keep going

More to explore in Build New.

All Build New resources →
let's talk

Got a problem like this one?

Tell us what's stuck. A real person replies within one business day.

Talk to our team →

Talk to people who know software, not a sales script.

Your first call is with Aja, our VP of Sales. He'll help make sure you're solving the right problem. Here's what you'll cover together:

  1. What you're trying to accomplish

    The business goal first, then the technology.

  2. Possible approaches

    And the tradeoffs of each, in plain language.

  3. Risks you may not have considered

    Technical and business, before they cost you.

  4. Whether AI changes the math

    What's practical, and what's just hype for your project.

  5. Sensible next steps

    Even if the right next step is not us.

book-a-call.ics

Loading the scheduler…

Open the booking page →

Some problems are easier to explain in writing. Send us a few lines about what you're working on, and we'll reply within one business day. Helpful to include:

  1. What the software does, or should do
  2. What's stuck, or what's worrying you
  3. Any deadline or budget you have in mind
note.md

Loading the form…