Problem 38
Build a Filterable Product Catalog API
MEDIUMBUILD
REST APIs / Routes+4
REST APIs / RoutesFastAPIPath ParametersQuery ParametersFiltering
You are building the read side of a product catalog API. Clients need to browse products by category, filter by price range, and look up a single product by its ID.
Implement two routes in the FastAPI app in main.py:
GET /products— returns all products, or a filtered subset when query parameters are provided.GET /products/{product_id}— returns the product with that ID, or a 404 response if it does not exist.
The product data is already defined in the starter file — do not modify it.
Requirements
GET /productswith no query parameters returns all products as a JSON array.GET /products?category=electronicsreturns only products whosecategorymatches the value (case-insensitive).GET /products?min_price=50returns only products withprice >= 50.0.GET /products?max_price=100returns only products withprice <= 100.0.GET /products?in_stock=truereturns only products wherein_stockisTrue;in_stock=falsereturns only products wherein_stockisFalse.- Multiple query parameters combine with AND logic — all active filters must match.
GET /products/{product_id}returns the matching product as a JSON object, or HTTP 404 if no product has that ID.
Examples
Example 1
Input
GET /products?category=electronics&min_price=60
Output
[{"id": "p002", ...}, {"id": "p005", ...}]Note
Both filters apply: category must be 'electronics' AND price must be >= 60. Keyboard (149.99) also matches, but this example shows the pattern — actual results depend on the starter dataset.
Example 2
Input
GET /products/p001
Output
{"id": "p001", "name": "Mechanical Keyboard", "category": "electronics", "price": 149.99, "in_stock": true}Note
Returns the single product with id 'p001'.
Example 3
Input
GET /products/p999
Output
HTTP 404
Note
No product with id 'p999' exists.
Constraints
- Do not modify the
PRODUCTSlist in the starter file. - All query parameters are optional. Omitted parameters do not filter.
- Category comparison is case-insensitive:
?category=Electronicsand?category=electronicsmust return the same results.
Follow-up
Right now filters are applied in Python after fetching all products. How would you restructure this if the product data were in a SQL database instead of an in-memory list?
Hints
Console output will appear here...