Skip to main content

FastAPI Overview

IFastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

It is designed to be easy to use and efficient, with high performance comparable to NodeJS and Go frameworks.

FastAPI is built on top of Starlette, a high-performance asynchronous framework, and Pydantic, a powerful data validation and serialization library. It combines the best features of these libraries to provide a straightforward and efficient way to build APIs.

History

FastAPI was created by Sebastián Ramírez and released in 2018. It quickly gained popularity due to its speed and ease of use. It is now one of the most popular Python frameworks for building APIs.

Features of FastAPI

  1. Fast: FastAPI is designed to be one of the fastest Python frameworks available, thanks to its use of asynchronous programming and high-performance components.

  2. Easy to use: FastAPI is designed to be easy to use, with a simple and intuitive API. It provides automatic generation of API documentation using OpenAPI and JSON Schema.

  3. Type checking: FastAPI leverages Python type hints to provide automatic data validation and serialization. It uses Pydantic models to define request and response types, making it easy to handle data validation and serialization.

  4. Asynchronous support: FastAPI is built on top of Starlette, which is an asynchronous framework. This allows you to write asynchronous code using Python's async and await keywords, enabling high-performance and concurrent API operations.

  5. Dependency injection: FastAPI supports dependency injection, allowing you to easily manage and inject dependencies into your API endpoints. This makes it simple to organize and modularize your code.

  6. WebSocket support: FastAPI provides built-in support for WebSocket communication, allowing you to easily build real-time applications.

  7. Authentication and authorization: FastAPI provides built-in support for adding authentication and authorization to your API endpoints. It supports various authentication methods, such as OAuth2, JWT, and more.

Now, let's dive into some examples to see these features in action.

Example 1: Creating a Simple API with FastAPI

Let's start by creating a simple API using FastAPI. We'll create a /hello endpoint that returns a JSON response with a greeting message.

from fastapi import FastAPI

app = FastAPI()

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

In this example, we import the FastAPI class from the fastapi module. We then create an instance of FastAPI and define an endpoint using the @app.get decorator. The hello function is the handler for the /hello endpoint, which returns a JSON response with a greeting message.

To run the API, we can use the following command:

uvicorn main:app --reload

Now, if we visit http://localhost:8000/hello in our browser, we should see the JSON response: {"message": "Hello, FastAPI!"}.

Example 2: Request Validation and Serialization

FastAPI uses Pydantic models for request validation and serialization. Let's modify our previous example to validate and serialize the request data.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class HelloRequest(BaseModel):
name: str

@app.post("/hello")
def hello(request: HelloRequest):
return {"message": f"Hello, {request.name}!"}

In this example, we define a HelloRequest model using Pydantic. The model has a single field name of type str. We then modify the /hello endpoint to accept a HelloRequest object as the request body. FastAPI automatically validates the request body against the model and deserializes it.

If we send a POST request to http://localhost:8000/hello with a JSON body like {"name": "John"}, the API will respond with {"message": "Hello, John!"}.

Example 3: Asynchronous Endpoints

FastAPI allows you to write asynchronous code using Python's async and await keywords. This enables high-performance and concurrent API operations. Let's modify our previous example to make the /hello endpoint asynchronous.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class HelloRequest(BaseModel):
name: str

@app.post("/hello")
async def hello(request: HelloRequest):
return {"message": f"Hello, {request.name}!"}

In this example, we add the async keyword to the hello function to make it asynchronous. This allows the function to use await to pause execution and wait for other asynchronous operations.

Example 4: Dependency Injection

FastAPI supports dependency injection, allowing you to easily manage and inject dependencies into your API endpoints. Let's modify our previous example to inject a dependency into the /hello endpoint.

from fastapi import Depends, FastAPI
from pydantic import BaseModel

app = FastAPI()

class HelloRequest(BaseModel):
name: str

def get_greeting():
return "Hello"

@app.post("/hello")
async def hello(request: HelloRequest, greeting: str = Depends(get_greeting)):
return {"message": f"{greeting}, {request.name}!"}

In this example, we define a get_greeting function that returns the greeting message. We then modify the hello endpoint to inject the greeting message as a dependency. FastAPI automatically resolves the dependency and passes it to the endpoint function.

For more information and detailed documentation, you can visit the official FastAPI website: https://fastapi.tiangolo.com/.