Skip to main content

Explain Python FastAPI

 

Introduction to FastAPI 🚀

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. It is based on Starlette (for web handling) and Pydantic (for data validation). It is known for its speed, automatic OpenAPI documentation, and easy data validation.


🌟 Key Features of FastAPI

Blazing Fast: Comparable to Node.js & Go (thanks to Starlette & Pydantic).
Automatic API Documentation: Comes with Swagger UI (/docs) & ReDoc (/redoc).
Built-in Data Validation: Uses Pydantic for request & response validation.
Asynchronous Support: Built-in support for async and await.
Dependency Injection: Easy-to-use dependency injection system.
Security: Provides built-in authentication & authorization mechanisms.


🔧 Installing FastAPI

Before you start, install FastAPI and Uvicorn (ASGI server):

pip install fastapi uvicorn

🚀 Creating Your First FastAPI App

Let's build a simple Hello, World! API.

📌 Code: FastAPI Basic Example

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def home():
    return {"message": "Hello, World!"}

# Run the app using: uvicorn main:app --reload

How to Run the FastAPI App

Save the file as main.py and start the server:

uvicorn main:app --reload

Now, visit:
📌 Swagger UIhttp://127.0.0.1:8000/docs
📌 ReDoc UIhttp://127.0.0.1:8000/redoc


📌 Creating RESTful API Endpoints

FastAPI supports GET, POST, PUT, DELETE methods.

✅ Example: Handling API Requests

from fastapi import FastAPI

app = FastAPI()

# GET request
@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id, "message": "Item retrieved"}

# POST request
@app.post("/items/")
async def create_item(item: dict):
    return {"message": "Item created", "item": item}

📌 Test it using Swagger UI: http://127.0.0.1:8000/docs


📌 Using Pydantic for Data Validation

FastAPI uses Pydantic models for automatic data validation.

✅ Example: Validating User Data

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()

# Pydantic Model
class User(BaseModel):
    id: int
    name: str
    email: EmailStr

# POST request with validation
@app.post("/users/")
async def create_user(user: User):
    return {"message": "User created", "user": user}

📌 Request Body (JSON):

{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com"
}

🚫 If an invalid email is provided, FastAPI automatically returns an error.


📌 Query Parameters and Path Variables

FastAPI supports query parameters and path variables.

✅ Example: Using Query Parameters

@app.get("/search/")
async def search_items(q: str, limit: int = 10):
    return {"query": q, "limit": limit}

👉 Example Request:

GET /search/?q=fastapi&limit=5

👉 Response:

{
  "query": "fastapi",
  "limit": 5
}

📌 Handling Request Headers & Form Data

FastAPI can extract headers, form data, and cookies.

✅ Example: Getting Headers

from fastapi import Request

@app.get("/headers/")
async def read_headers(request: Request):
    return {"user-agent": request.headers.get("user-agent")}

✅ Example: Handling Form Data

from fastapi import Form

@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
    return {"message": f"User {username} logged in"}

📌 Send a form request (not JSON) with username and password.


📌 FastAPI with Database (SQLAlchemy)

FastAPI integrates well with databases like PostgreSQL, MySQL, SQLite using SQLAlchemy.

✅ Example: FastAPI + SQLite (SQLAlchemy)

from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from database import SessionLocal, engine, Base
from models import User

app = FastAPI()

# Dependency to get the database session
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users/")
async def get_users(db: Session = Depends(get_db)):
    users = db.query(User).all()
    return users

📌 Database connection and models would be defined in separate files (database.py & models.py).


📌 Authentication with FastAPI

FastAPI supports authentication methods like:

  • OAuth2
  • JWT (JSON Web Tokens)
  • API Key-based Authentication

✅ Example: OAuth2 with JWT

from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/protected/")
async def protected_route(token: str = Depends(oauth2_scheme)):
    return {"message": "You are authenticated", "token": token}

Now, you must pass a valid token to access /protected/.


📌 FastAPI WebSockets (Real-time Communication)

FastAPI supports WebSockets for real-time communication.

✅ Example: WebSocket Echo Server

from fastapi import WebSocket

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"You sent: {data}")

Use WebSockets for real-time chat apps, stock price updates, etc..


📌 Automatic API Documentation

FastAPI automatically generates API docs.

👉 No extra configuration is needed!


🎯 Conclusion

FastAPI is a powerful yet simple framework that makes building APIs fast and efficient.

💡 Why Choose FastAPI? ✅ Fast performance (near Go & Node.js speed)
✅ Automatic request validation & documentation
✅ Asynchronous support (async/await)
✅ Easy database & authentication integration


Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...