FastAPI — Basic (50+ Coding Exercises)
- Create a minimal FastAPI app with a GET
/healthreturning{\"status\": \"ok\"}. - Run the app with Uvicorn and verify docs at
/docs. - Add GET
/items/{item_id}returning the id as JSON. - Add query params
limitandoffsetto GET/items. - Create a Pydantic model
ItemCreate(name, price)and POST/itemsto accept it. - Return
201on successful create and include a generatedid. - Validate
price >= 0and return validation error automatically. - Add response model
ItemPublicthat excludes internal fields. - Raise
HTTPException(404)when item not found in GET/items/{id}. - Implement in-memory CRUD storage for items (dict-based).
- Implement PUT
/items/{id}to update an item. - Implement DELETE
/items/{id}to delete an item. - Add tags to group endpoints in OpenAPI docs.
- Create an
APIRouterfor/itemsroutes and include it in the app. - Create an
APIRouterfor/usersroutes and include it. - Implement middleware that adds an
X-Request-Idheader if missing. - Return the request id in every response.
- Add CORS middleware allowing a specific frontend origin.
- Add a dependency
get_now()and inject it into an endpoint returning server time. - Add a dependency that validates an API key header for a protected endpoint.
- Create a settings class loading
DATABASE_URLfrom env (stub if not present). - Add startup event to initialize a global resource (e.g., DB client placeholder).
- Add shutdown event to close the global resource.
- Add GET
/headersthat returns selected request headers. - Add GET
/cookiesthat reads a cookie and returns it. - Add POST
/uploadthat accepts a file upload and saves it to disk. - Enforce max upload size (basic check) and reject with 413.
- Add POST
/formthat accepts form fields and returns parsed values. - Add an endpoint that returns plain text using
Response. - Add custom JSONResponse with custom headers for one endpoint.
- Add error handler for
HTTPExceptionto return a consistent error format. - Add error handler for request validation errors to match your error format.
- Add
/api/v1router prefix and move endpoints under it. - Add
/api/v2/healthas a separate versioned endpoint. - Implement a simple “todo” resource with CRUD endpoints in-memory.
- Add pagination to list endpoints (limit/offset).
- Add sorting for list endpoints (e.g.,
sort=name). - Add filtering by min/max price for items.
- Add a dependency that logs request duration (print or logger).
- Add
BackgroundTasksto enqueue a dummy task after creating an item. - Add unit tests for
/healthusingTestClient. - Add tests for create/get/update/delete item endpoints.
- Add tests for validation errors (negative price).
- Add tests for 404 errors on missing item.
- Add a simple
Makefileor script section (documented) to run the app. - Add an endpoint that returns a list of items with response_model validation.
- Add
response_model_exclude_none=Trueand verify output. - Add endpoint that uses path+query+body all together.
- Add endpoint that uses a dependency to parse common query params.
- Add endpoint that returns current app version from settings.
- Add endpoint that accepts a list of items and bulk-creates them.
- Add endpoint that deletes all items (protected by API key dependency).