如何在Sanic-OpenAPI中为查询参数配置允许可选值?(含timeframe参数指定示例)
How to Set Allowed Values for Query Parameters in Sanic-OpenAPI 0.7.1
Hey there! Since you're working with Sanic-OpenAPI 0.7.1 and Python 3.8, defining allowed values for your timeframe query parameter is simple. You just need to leverage the enum parameter in the openapi.parameter decorator to specify valid options. Here's the updated code for your endpoint:
from sanic import Sanic, json from sanic_openapi import openapi app = Sanic("test_service") @app.get("/test") @openapi.tag("Test") @openapi.summary('Get Data') @openapi.description('Just a demo') @openapi.parameter( "timeframe", str, location="query", enum=["day", "week", "month"], # This defines your allowed values description="Timeframe for data retrieval (valid options: day, week, month)", required=False # Set to True if this parameter is mandatory ) async def test_handler(request): # Get the parameter value (with an optional default) timeframe = request.args.get("timeframe", "day") # Important: Sanic-OpenAPI 0.7.1 doesn't auto-validate enum values # Add manual validation to reject invalid inputs if timeframe not in ["day", "week", "month"]: return json( {"error": "Invalid timeframe. Allowed values: day, week, month"}, status=400 ) # Your business logic here return json({"message": f"Fetching data for timeframe: {timeframe}"})
Key Details:
- The
enum=["day", "week", "month"]argument tells Sanic-OpenAPI to list these values in the auto-generated Swagger documentation (accessible at/swaggerby default), so API consumers can see valid options at a glance. - Sanic-OpenAPI 0.7.1 doesn't automatically validate incoming requests against the enum values—you'll need to add the manual check in your handler to ensure only valid values are processed. This prevents invalid inputs from reaching your business logic.
- If you want
timeframeto be a required parameter, just setrequired=Truein theopenapi.parameterdecorator. The Swagger docs will mark it as mandatory, and you can adjust your handler to handle missing values appropriately.
内容的提问来源于stack exchange,提问作者Valiant
相关产品推荐
相关产品推荐

