CodexBloom - Programming Q&A Platform

Handling Custom Query Parameters in FastAPI with Type Validation and Defaults

👀 Views: 58 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-27
fastapi query-parameters validation Python

I'm getting frustrated with I'm trying to configure I'm sure I'm missing something obvious here, but I'm working on a FastAPI application and I need to create an endpoint that accepts a query parameter with specific validation rules. The endpoint should accept a query parameter `page` which should be an integer and defaults to `1` if not provided. However, I'm working with issues with type validation when I try to set a default value. When I use `Optional[int]` for the query parameter, I get the following behavior: `value is not a valid integer`. Here's the code I'm using: ```python from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(page: int = Query(1, ge=1)): return {"page": page} ``` I've tried removing `Optional` since the documentation mentions that FastAPI handles defaults correctly, but I still receive the same behavior. What am I doing wrong here? How can I ensure that `page` is validated properly and defaults to `1` without throwing an behavior? Additionally, if I want to extend this to include another query parameter, say `size` with a default of `10`, while ensuring both parameters are validated, what would that look like? Any guidance or clarification on how type validation works with defaults in FastAPI would be greatly appreciated. The project is a microservice built with Python. What's the correct way to implement this? I'm working in a CentOS environment. Any ideas what could be causing this? What are your experiences with this?