Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Path Parameter Basics📚 Path Types📚 Validation📚 Required vs Optional📚 Path Converters📚 Order Matters📚 Complex Paths
Fastapi/Path Parameters/Required Optional

Required vs Optional Path Parameters 🎯

Path parameters can be required (mandatory) or optional (with defaults). Understanding the difference is crucial for API design.

What's the Difference?

Required Path Parameters

A required path parameter MUST be provided in the URL, or the endpoint won't match:

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    # user_id is REQUIRED
    # /users/123 ✅ Works
    # /users ❌ Error - endpoint not found
    return {"user_id": user_id}

Optional Path Parameters

Optional path parameters can be omitted. However, in FastAPI, path parameters are always required by default. To make them optional, you need a different approach using route ordering:

# Multiple routes for flexibility
@app.get("/users/{user_id}")
async def get_user(user_id: int):
    # Specific user
    return {"user_id": user_id}

@app.get("/users/list")
async def list_users():
    # List all users - handles the "optional" case
    return {"users": []}

The Key Difference

FeatureRequiredOptional
Must be in URLYes ✅No
Default valueNoneYes
Endpoint matches without itNoYes (different endpoint)
Error if missing404 Not FoundUses default or alternate route

Real-World Example

from fastapi import FastAPI

app = FastAPI()

# Required: user_id must be provided
@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"id": user_id, "name": f"User {user_id}"}

# Handles the "list all" case
@app.get("/users")
async def list_users():
    return {"users": [
        {"id": 1, "name": "User 1"},
        {"id": 2, "name": "User 2"}
    ]}

# Multiple levels
@app.get("/users/{user_id}/posts/{post_id}")
async def get_post(user_id: int, post_id: int):
    # Both user_id and post_id are REQUIRED
    return {"user_id": user_id, "post_id": post_id}

API Calls

# Required parameter provided ✅
curl http://localhost:8000/users/123
# Returns: {"id": 123, "name": "User 123"}

# Required parameter missing ❌
curl http://localhost:8000/users
# Returns: 404 Not Found

# Use list endpoint instead ✅
curl http://localhost:8000/users
# Returns: {"users": [...]}

Design Principle

Path parameters are always required in REST APIs. If you need optional parameters, use:

  • **Query parameters** for optional filters
  • **Multiple routes** for different use cases
  • **Different endpoints** for different operations

Good API Design

# ✅ Good: Clear required parameters
@app.get("/products/{product_id}")
async def get_product(product_id: int):
    return {"id": product_id}

@app.get("/products")
async def list_products():
    return {"products": []}

# ✅ Good: Optional query parameters for filtering
@app.get("/products")
async def search_products(
    category: Optional[str] = None,
    min_price: Optional[float] = None
):
    return {"products": []}

🔑 Key Takeaways

  • ✅ Path parameters in FastAPI are always **required**
  • ✅ Required parameters must be included in the URL
  • ✅ If a parameter is missing, the endpoint won't match (404)
  • ✅ Use multiple routes to handle "optional" scenarios
  • ✅ Use query parameters for truly optional filters
  • ✅ REST principle: path is for resource identification
  • ✅ Query string is for filtering/options


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn