FastAPI is a Python web framework based on standard Python type hints. It leverages the power of the Starlette web framework for handling HTTP requests and responses and Pydantic for data validation. Some of the key features of FastAPI include:
python -m venv myenv
myenv\Scripts\activate
- On Linux/Mac:
source myenv/bin/activate
pip
:pip install fastapi uvicorn
Here is a simple example of a FastAPI application with a single API endpoint:
from fastapi import FastAPI
# Create a FastAPI app instance
app = FastAPI()
# Define a GET endpoint
@app.get("/")
def read_root():
return {"Hello": "World"}
To run this application, save the above code in a file named main.py
and run the following command:
uvicorn main:app --reload
Now, if you open your browser and go to http://127.0.0.1:8000
, you will see the JSON response {"Hello": "World"}
.
FastAPI makes it easy to handle different types of requests and responses. Here is an example of handling a POST request:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# Define a data model using Pydantic
class Item(BaseModel):
name: str
price: float
# Define a POST endpoint
@app.post("/items/")
def create_item(item: Item):
return item
In this example, the create_item
function expects a JSON payload in the request body that matches the Item
data model. It then returns the same item as the response.
Path parameters are used to capture values from the URL path. Here is an example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
Query parameters are used to pass additional information in the URL. Here is an example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
Pydantic is a powerful library for data validation in FastAPI. It allows you to define data models with strict type checking. Here is an example of more complex data validation:
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
class User(BaseModel):
name: str
email: EmailStr
age: int
@app.post("/users/")
def create_user(user: User):
return user
In this example, the EmailStr
type ensures that the email
field in the User
model is a valid email address.
FastAPI provides built - in support for various authentication and authorization mechanisms. Here is a simple example of using HTTP Basic Authentication:
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
@app.get("/protected/")
def read_protected(credentials: HTTPBasicCredentials = Depends(security)):
return {"message": "This is a protected route"}
FastAPI can be easily integrated with different databases. Here is an example of integrating with SQLite using SQLAlchemy:
from fastapi import FastAPI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, declarative_base
app = FastAPI()
# Create a SQLite database
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Define a database model
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
Base.metadata.create_all(bind=engine)
# Dependency to get a database session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/items/")
def create_item(name: str, db = Depends(get_db)):
item = Item(name=name)
db.add(item)
db.commit()
db.refresh(item)
return item
You can use the TestClient
from fastapi.testclient
to test your FastAPI applications. Here is an example:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Hello": "World"}
FastAPI is a powerful and easy - to - use Python web framework for building REST APIs. It provides a wide range of features such as high performance, automatic documentation, and seamless integration with other libraries. By following the concepts and best practices outlined in this guide, you can create efficient and robust REST APIs using FastAPI.