DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

Query Params & Validation: Making APIs Flexible and Secure

What are Query Parameters?

Query parameters let users filter and customize API responses
without changing the endpoint itself.

Instead of /products/electronics, you write:
/products?category=electronics&limit=5

Clean, flexible, and powerful.

What is Input Validation?

Validation ensures bad data never enters your system.
If a user sends an empty search term or a negative price,
your API should reject it immediately, not crash later.

My 3 Endpoints for Day 5

1. Search with Validation

@app.get("/search")
def search(q: str = Query(min_length=1, description="Search term")):
    return {
        "query": q,
        "message": f"Searching for: {q}"
    }
Enter fullscreen mode Exit fullscreen mode

If q is empty : FastAPI automatically returns a 422 error.
No extra code needed. That's Pydantic doing the work.

2. Products with Optional Filters

@app.get("/products")
def get_products(
    category: str = Query(default="all"),
    limit: int = Query(default=10, ge=1, le=100)
):
    return {
        "category": category,
        "limit": limit,
        "message": f"Fetching {limit} products from: {category}"
    }
Enter fullscreen mode Exit fullscreen mode

limit has a minimum of 1 and maximum of 100

users can't request 0 or 10,000 products.

3. POST with Pydantic Model

class Item(BaseModel):
    name: str
    price: float
    quantity: int

@app.post("/items")
def create_item(item: Item):
    return {
        "message": "Item created successfully",
        "item": item
    }
Enter fullscreen mode Exit fullscreen mode

Pydantic automatically validates types
if price is a string instead of a float, it's rejected.

Screenshots

Search Error

Search success

Product success

Items success

Lessons Learned

Validation isn't optional in production APIs.
Never trust user input, always validate at the boundary
before it touches your business logic or database.

Day 5 done. 25 more to go.

GDGoCBowen30dayChallenge

Top comments (0)