Scalability refers to the ability of an application to handle an increasing amount of work, such as more users, more requests, or larger data volumes, without a significant decrease in performance. There are two main types of scalability: vertical scalability (increasing the resources of a single server, like adding more RAM or CPU) and horizontal scalability (adding more servers to distribute the load).
First, create a virtual environment and install FastAPI and Uvicorn (a lightning - fast ASGI server for Python).
python -m venv myenv
source myenv/bin/activate # On Windows, use `myenv\Scripts\activate`
pip install fastapi uvicorn
Here is a simple example of a FastAPI application with a single endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
To run the application, use the following command:
uvicorn main:app --reload
Now, you can access the API at http://127.0.0.1:8000
.
FastAPI makes it easy to handle different types of requests and responses. For example, handling a POST request with a JSON body:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return item
FastAPI can be easily integrated with various databases. For example, using SQLAlchemy for a relational database:
from fastapi import FastAPI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, declarative_base
app = FastAPI()
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
price = Column(Integer)
Base.metadata.create_all(bind=engine)
@app.post("/items/")
def create_item(name: str, price: int):
db = SessionLocal()
new_item = Item(name=name, price=price)
db.add(new_item)
db.commit()
db.refresh(new_item)
db.close()
return new_item
FastAPI supports asynchronous programming out - of - the - box. You can use async def
to define asynchronous endpoints:
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/async/")
async def read_async():
await asyncio.sleep(1)
return {"message": "This is an asynchronous response"}
Caching can significantly improve the performance of your application. You can use libraries like cachetools
to implement caching in FastAPI:
from fastapi import FastAPI
from cachetools import TTLCache
app = FastAPI()
cache = TTLCache(maxsize=100, ttl=300)
@app.get("/cached/")
def read_cached():
if "data" in cache:
return cache["data"]
data = {"message": "This data is cached"}
cache["data"] = data
return data
Proper error handling is crucial for a scalable application. FastAPI provides built - in exception handlers. You can also create custom exception handlers:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/error/")
def read_error():
raise HTTPException(status_code=404, detail="Item not found")
Logging helps in debugging and monitoring the application. You can use Python’s built - in logging
module:
import logging
from fastapi import FastAPI
app = FastAPI()
logging.basicConfig(level=logging.INFO)
@app.get("/log/")
def read_log():
logging.info("This is an info log message")
return {"message": "Check the logs"}
Testing is essential to ensure the reliability of your application. You can use pytest
to write tests for FastAPI applications:
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 web framework for building scalable applications. Its high performance, automatic documentation, and support for asynchronous programming make it an excellent choice for modern web development. By following the common and best practices outlined in this blog post, you can build robust, scalable, and maintainable applications with FastAPI.