You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 /swagger by 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 timeframe to be a required parameter, just set required=True in the openapi.parameter decorator. The Swagger docs will mark it as mandatory, and you can adjust your handler to handle missing values appropriately.

内容的提问来源于stack exchange,提问作者Valiant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:07:50