Home › Interview Questions › How would you implement a FastAPI endpoint that us…

How would you implement a FastAPI endpoint that uses query parameters for department, min_salary, and sort_by, validated via Pydantic?

🟡 Medium Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

FastAPI automatically parses query parameters from the URL and can validate them using Pydantic models. Define a Pydantic model that represents the query parameters: department: str, min_salary: int = Field(..., ge=0), sort_by: str = Field(default='salary'). Then declare the endpoint to accept this model via Depends. FastAPI will instantiate the model, perform validation, and inject the validated data into the path operation. Inside the handler you can use the validated values to filter or sort a database query. Example: from fastapi import FastAPI, Depends; from pydantic import BaseModel, Field; app = FastAPI(); class EmployeeQuery(BaseModel): department: str; min_salary: int = Field(..., ge=0); sort_by: str = Field(default='salary'); @app.get('/employees') async def get_employees(q: EmployeeQuery = Depends()): # use q.department, q.min_salary, q.sort_by to query DB return {'msg': 'ok'} The Pydantic model ensures that min_salary is a non-negative integer and that sort_by defaults to 'salary' if not provided. FastAPI will automatically return a 422 Unprocessable Entity response if validation fails, providing clear error messages. This approach keeps the endpoint logic clean and separates validation concerns from business logic.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500