FastAPI Fast Modern Web Framework for Python

By Anurag Singh

Updated on Oct 22, 2024

FastAPI Fast Modern Web Framework for Python

In this blog post, we'll disucss about FastAPI fast modern web framework for Python.

FastAPI has quickly gained popularity as a web framework of choice for Python developers due to its high performance, ease of use, and modern features. It is designed to build APIs and web applications that are fast to develop, easy to maintain, and capable of handling production-level performance with minimal overhead.

We’ll explore what makes FastAPI stand out, how it compares to other popular frameworks, and how to get started building a simple API using FastAPI.

What is FastAPI?

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. It is built on top of Starlette for web handling and Pydantic for data validation, making it both lightweight and extremely fast.

FastAPI is asynchronous by default, which allows for handling many requests simultaneously, making it perfect for high-performance applications. It also features automatic data validation, interactive API documentation, and out-of-the-box support for asynchronous programming.

Key Features of FastAPI

FastAPI comes with several key features that set it apart from other frameworks, such as Flask or Django:

Speed: FastAPI is among the fastest web frameworks available in Python. It is nearly as fast as frameworks like Node.js and Go, thanks to its asynchronous nature and the use of ASGI (Asynchronous Server Gateway Interface).

Automatic Interactive API Documentation: FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc, which makes it easier for developers to interact with the API during development.

Built-in Data Validation: Using Pydantic, FastAPI validates incoming requests based on Python's type annotations. This ensures the correctness of data inputs without writing extensive validation code.

Asynchronous Support: FastAPI allows you to write both synchronous and asynchronous views using async and await. This is especially useful when working with I/O-bound operations like database queries or external API requests.

Type Annotations: FastAPI takes advantage of Python type hints to automatically generate request parameters, query strings, and body validation schemas, all while making your code more explicit and easier to maintain.

Dependency Injection: FastAPI has a powerful dependency injection system that makes it easy to manage dependencies and reuse components across different parts of your application.

FastAPI vs Flask vs Django

FeatureFastAPIFlaskDjango
SpeedExtremely fast, asynchronous by defaultSlower, single-threaded synchronousSlower, synchronous by default
Type AnnotationsFull support for type hints and validationNo native supportNo native support
Async SupportBuilt-in async/awaitRequires extensions for asyncLimited async support
ORMNone (but supports SQLAlchemy and others)None (requires extensions)Built-in (Django ORM)
DocumentationAutomatically generated (Swagger/ReDoc)Manual or use Flask-RESTPlusNo auto docs (requires packages)

FastAPI shines when you need a lightweight framework with powerful data validation, asynchronous request handling, and auto-generated documentation. Flask is more lightweight and flexible but lacks some of the built-in conveniences of FastAPI. Django, on the other hand, is a full-fledged web framework with an ORM, admin panel, and all-in-one solution, but it can be overkill for building APIs.

Getting Started with FastAPI

Now, let’s dive into building a simple FastAPI project. We’ll create a REST API that manages a list of books. You’ll learn how to define routes, handle request parameters, and validate data.

Prerequisites

To follow along, you’ll need:

Python 3.7 or later installed.

FastAPI and Uvicorn installed. You can install them using the following commands:

pip install fastapi
pip install "uvicorn[standard]"

Creating a Simple API

Start by creating a new file called main.py and add the following code:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# Define the Book model
class Book(BaseModel):
    title: str
    author: str
    year: int

# In-memory book database
books_db = []

# Get all books
@app.get("/books")
def get_books():
    return books_db

# Add a new book
@app.post("/books")
def add_book(book: Book):
    books_db.append(book.dict())
    return book

# Get a single book by title
@app.get("/books/{title}")
def get_book(title: str):
    for book in books_db:
        if book["title"] == title:
            return book
    return {"error": "Book not found"}

# Delete a book by title
@app.delete("/books/{title}")
def delete_book(title: str):
    for i, book in enumerate(books_db):
        if book["title"] == title:
            del books_db[i]
            return {"message": "Book deleted"}
    return {"error": "Book not found"}

Running the Application

To run the FastAPI application, you need to use Uvicorn, an ASGI server. Run the following command in your terminal:

uvicorn main:app --reload

Once the server is running, you can visit http://127.0.0.1:8000/docs to access the automatically generated Swagger UI, where you can interact with the API.

Testing the API

  • GET /books: Fetch the list of books (Initially empty).
  • POST /books: Add a new book by sending a JSON payload like:
{
  "title": "1984",
  "author": "George Orwell",
  "year": 1949
}
  • GET /books/{title}: Retrieve a book by its title.
  • DELETE /books/{title}: Delete a book by its title.

Best Practices with FastAPI

Use Type Annotations: Leverage Python's type hints to make your API explicit and reduce bugs. This is also crucial for FastAPI to generate documentation and validate data.

Structure Your Project: As your application grows, consider structuring it into separate files and modules. Use a package structure to organize routers, models, and dependencies.

Handle Errors Gracefully: FastAPI makes it easy to handle errors using custom exception handlers. Create custom error classes to handle specific cases and return meaningful error messages to users.

Testing: FastAPI supports Python's built-in unittest and third-party libraries like pytest. Always write tests for your routes and business logic to ensure API reliability.

Security: FastAPI provides tools for authentication and authorization. Use OAuth2 or JWT for secure access to APIs.

Conclusion

FastAPI is a powerful and flexible framework for building APIs quickly and efficiently in Python. Its speed, automatic documentation generation, and intuitive design make it an excellent choice for developers building modern, high-performance web applications. Whether you are building small APIs or complex microservices, FastAPI can help you get your project up and running quickly, without sacrificing performance or readability.

If you are considering using FastAPI for your next project, the framework’s combination of simplicity, speed, and scalability makes it a compelling choice, especially if you need async support or type-safe request validation.

Checkout our dedicated servers India, Instant KVM VPS, and Web Hosting India