FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It was created by Sebastián RamÃrez and is designed to be easy to use, fast to develop with, and provide automatic validation of request and response data using Python’s type hints.
Key features of FastAPI include:
- Fast Execution: It is built on top of Starlette and Pydantic, making use of asynchronous programming for high performance.
- Automatic Documentation: FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc based on the Python type hints provided in your code.
- Type Annotations: FastAPI leverages Python type hints for request and response parameters, enabling automatic validation and generation of OpenAPI (formerly Swagger) documentation.
- Dependency Injection: It supports dependency injection, making it easy to organize and manage dependencies in your application.
- WebSocket Support: FastAPI includes support for WebSocket communication, allowing bidirectional communication between the client and server.
- Security Features: It includes built-in security features, such as OAuth2 and API key authentication, as well as support for dependency injection for managing security requirements.
Here’s a simple example of a FastAPI application:
from fastapi import FastAPI
app = FastAPI()
def read_root():
return {“Hello”: “World”}
def read_item(item_id: int, query_param: str = None):
return {“item_id”: item_id, “query_param”: query_param}
In this example, the read_root
function responds to the root endpoint (“/”) with a JSON response, and the read_item
function responds to the “/items/{item_id}” endpoint with the item_id and an optional query parameter.
To run a FastAPI application, you typically use the uvicorn
ASGI server:
uvicorn your_app_name:app --reload
Replace your_app_name
with the actual name of your Python file or module containing the FastAPI app instance.
FastAPI has gained popularity for its combination of speed, ease of use, and automatic documentation generation, making it a popular choice for building APIs with Python.
Here are some more features and concepts in FastAPI:
- Data Validation with Pydantic: FastAPI uses Pydantic models for data validation and serialization. By defining data models using Pydantic, you get automatic validation of request and response data based on the declared types.
python
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None - Path Parameters and Query Parameters: FastAPI supports path parameters, query parameters, and request bodies, allowing you to easily define and handle different types of data in your API.
python
def read_item(item_id: int, query_param: str = None):
return {"item_id": item_id, "query_param": query_param}
- Request and Response Objects: FastAPI provides
Request
andResponse
objects that you can use to access information about the incoming request and customize the outgoing response.pythonfrom fastapi import Request
def read_headers(request: Request):
return {“headers”: request.headers} - Dependency Injection: FastAPI has a built-in dependency injection system that allows you to organize and manage dependencies in your application. Dependencies can be automatically injected into route functions.
python
from fastapi import Depends, HTTPException
def get_current_user(api_key: str = Depends(get_api_key)):
# Dependency logic here
return User(api_key)
def read_current_user(current_user: User = Depends(get_current_user)):
return {“username”: current_user.username} - Security and Authentication: FastAPI includes built-in support for OAuth2, API key authentication, and other security features. You can easily add authentication and authorization to your routes.
python
security = OAuth2PasswordBearer(tokenUrl=“token”)from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
def read_current_user(token: str = Depends(security)):
# Verify token logic here
return {“token”: token} - Middleware Support: FastAPI supports the use of middleware to customize the behavior of your application. You can add middleware functions to handle tasks such as logging, authentication, or other pre-processing.
python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=[“*”],
allow_credentials=True,
allow_methods=[“*”],
allow_headers=[“*”],
)
These are just a few of the many features and capabilities of FastAPI. The framework is designed to be powerful, efficient, and easy to use, making it a great choice for building APIs in Python.
Above is the brief about FastAPI. Watch this space more updates on the latest trends in Technology