FastAPI vs Flask: Comparison

Tags
Item ID

Notion Link
Related to Content (1) (Production Pages)
Lesson
From Flask to FastAPI

Understanding the key differences between Flask and FastAPI can help developers make informed decisions on which framework to use based on their specific needs.

🚀 Performance

  • FastAPI is designed to be one of the fastest web frameworks for Python, especially when it comes to I/O bound operations. It is built on top of Starlette for the web parts and Pydantic for data validation and serialization.
  • Flask, on the other hand, is lightweight and flexible but does not inherently provide the same asynchronous capabilities that make FastAPI so fast.

📄 Type Annotations & Validation

  • FastAPI uses Python type hints in function signatures to validate input data and serialize output data. This allows for automatic data validation, serialization, and documentation generation.
  • Example:

    from pydantic import BaseModel
    
    class Recipe(BaseModel):
        id: int = None
        name: str
        ingredients: list[str]
    
    
    @app.post("/recipes")
    def create_recipe(recipe: Recipe):
        print(recipe.id, recipe.name)
        ...

    In this example, just by using type annotations, FastAPI knows the expected shape of the data, how to validate it, and how to serialize/deserialize it. The JSON input is automatically deserialized into an object. It's similar to how ORM models define and validate the structure of the data they handle.

  • With Flask, developers generally have to use extensions like Marshmallow to achieve similar functionality. It's more manual in comparison.