Many APIs have path parameters that only accept a few fixed values — an order status, for example: pending, shipped, or delivered. Instead of accepting a str and checking it by hand with if/else, declare the parameter as an Enum that inherits from str and Enum — FastAPI rejects unknown values with a 422 error on its own, generates docs with the list of choices, and the endpoint code no longer needs a branch for invalid values.
The Problem
Suppose you write an endpoint that lists orders by status. The familiar approach is to accept status as a str and branch through each value:
@app . get ( "/orders/{status}" ) def list_orders ( status : str ) : if status == "pending" : return { "orders" : [ "#1001" , "#1002" ] } elif status == "shipped" : return { "orders" : [ "#1003" ] } elif status == "delivered" : return { "orders" : [ "#1004" , "#1005" ] } return { "error" : "Trạng thái không hợp lệ" }
Enter fullscreen mode
Exit fullscreen mode
This has three weaknesses.…