
FastAPI
Learn essential concepts of path types in FastAPI.
This section covers path parameter types, including:
FastAPI automatically converts path parameters to specified types. This enables type safety and automatic validation.
from fastapi import FastAPI
import uuid
from datetime import datetime
app = FastAPI()
# String - default type
@app.get("/users/{username}")
async def get_user_by_name(username: str):
return {"username": username}
# Integer
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# Only accepts integers: /users/123 ✅
# /users/abc ❌ Returns 422 validation error
return {"user_id": user_id}
# Float
@app.get("/ratings/{rating}")
async def get_rating(rating: float):
# Accepts floats: /ratings/4.5 ✅
return {"rating": rating}
# UUID
@app.get("/resources/{resource_id}")
async def get_resource(resource_id: uuid.UUID):
# UUID validation: /resources/123e4567-e89b-12d3-a456-426614174000 ✅
return {"resource_id": resource_id}
# Boolean
@app.get("/toggle/{flag}")
async def toggle_feature(flag: bool):
# Accepts: true/True/True/TRUE, false/False/FALSE ✅
return {"flag": flag}# Integer validation
@app.get("/posts/{post_id}")
async def get_post(post_id: int):
# ✅ Valid: /posts/123
# ❌ Invalid: /posts/abc (422 Unprocessable Entity)
return {"post_id": post_id}
# Float validation
@app.get("/discounts/{percentage}")
async def apply_discount(percentage: float):
# ✅ Valid: /discounts/15.5
# ❌ Invalid: /discounts/abc
return {"percentage": percentage}
# UUID validation
@app.get("/files/{file_id}")
async def download_file(file_id: uuid.UUID):
# ✅ Valid: /files/550e8400-e29b-41d4-a716-446655440000
# ❌ Invalid: /files/invalid-uuid
return {"file_id": str(file_id)}Path types are used for:
Next step: Explore the advanced section for production patterns and optimization techniques.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward