How would you implement a FastAPI endpoint with employee_id as a path parameter and status, limit, offset as query parameters, all validated by Pydantic?
💡 Model Answer
FastAPI supports path parameters and query parameters out of the box. For the path parameter employee_id you can use Path(..., gt=0). For the query parameters, create a Pydantic model that includes status as an Enum, limit and offset with Field constraints. Example: from fastapi import FastAPI, Path, Depends; from pydantic import BaseModel, Field; from enum import Enum; app = FastAPI(); class StatusEnum(str, Enum): active='active'; completed='completed'; all='all'; class EmployeeQuery(BaseModel): status: StatusEnum = Field(default=StatusEnum.all); limit: int = Field(..., ge=1, le=100); offset: int = Field(..., ge=0); @app.get('/employees/{employee_id}') async def get_employee(employee_id: int = Path(..., gt=0), q: EmployeeQuery = Depends()): # use employee_id, q.status, q.limit, q.offset to fetch data return {'msg': 'ok'} The Path parameter ensures employee_id is a positive integer. The StatusEnum restricts status to a known set of values, preventing invalid input. The Field constraints on limit and offset enforce pagination limits. FastAPI will automatically validate and return a 422 error if any constraint is violated. This pattern keeps validation logic declarative and the endpoint function focused on 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