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

How would you implement a FastAPI endpoint that accepts query parameters for department, min_salary, and sort_by, validates them with Pydantic, and returns a filtered and sorted list of employees?

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

💡 Model Answer

Define a Pydantic model for the query: class EmployeeFilter(BaseModel): department: str | None = None; min_salary: int = 0; sort_by: Literal['id','department','salary'] = 'id'. In FastAPI, create an endpoint: @app.get("/employees") async def get_employees(filter: EmployeeFilter = Depends()): Inside, filter the in‑memory list: filtered = [e for e in employees if (filter.department is None or e['department'] == filter.department) and e['salary'] >= filter.min_salary]. Sort: sorted_emps = sorted(filtered, key=lambda e: e[filter.sort_by]). Return sorted_emps. FastAPI automatically parses query parameters into the Pydantic model, validates types, and returns 422 on invalid input. Complexity remains O(n log n) for sorting. This pattern keeps validation logic separate, makes the endpoint clean, and leverages FastAPI’s dependency injection.

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