1

I'm reading the tutorial on Path Parameter Validation.

I want to allow the strings "a" "b" and "c" as possible parameter values. I want these values to show up in the OpenAPI documentation (i.e., FastAPI's automatic docs), so that the API user does not have to guess them. How can I make these values show up in the documentation?

Here is my implementation:

from fastapi import FastAPI, HTTPException

app = FastAPI()

parameters = ["a", "b", "c"]

@app.get("/endpoint/{parameter}")
def endpoint(parameter: str):
    if parameter not in parameters:
        raise HTTPException(status_code=400, detail="parameter must be a, b, or c")
    return {"parameter": parameter}
Chris
  • 18,724
  • 6
  • 46
  • 80
Osvald Laurits
  • 1,228
  • 2
  • 17
  • 32
  • 3
    Does using an Enum satisfy your documentation need? https://pydantic-docs.helpmanual.io/usage/types/#enums-and-choices It's also shown in the tutorial page you linked: https://fastapi.tiangolo.com/tutorial/path-params/#create-an-enum-class – MatsLindh Sep 07 '21 at 11:26
  • Hi! I'm not sure what you mean by within then OpenAPI. Generally, this is done with the docstrings if you want it front and center. Also, have you looked at this? https://fastapi.tiangolo.com/tutorial/metadata/ – astrochun Sep 07 '21 at 11:36
  • By within the OpenAPI I mean the documentation available at http://127.0.0.1:8000/docs . Enum satisfies my documentation need. Thank you MatsLindh! – Osvald Laurits Sep 07 '21 at 12:09

2 Answers2

0

Use an Enum for parameter validation and the allowed values will appear in the documentation site.

from enum import Enum

from fastapi import FastAPI, HTTPException

app = FastAPI()

class AllowedParameterValues(str, Enum):
    a = "a"
    b = "b"
    c = "c"


@app.get("/endpoint/{parameter}")
def endpoint(parameter: AllowedParameterValues):
    return {"parameter": parameter}
Brylie Christopher Oxley
  • 1,684
  • 1
  • 17
  • 34
0

Option 1

You could use enums, by creating an Enum sub-class, as described in FastAPI documentation:

from enum import Enum

class MyParam(str, Enum):
    a= "a"
    b= "b"
    c= "c"

@app.get("/{my_param}")
def index(my_param: MyParam):
    return {"my_param": my_param}

Option 2

Alternatively, you could use Literal type, which allows you to specify that a parameter may accept only specific Literal values:

from typing import Literal

@app.get("/{my_param}")
def index(my_param: Literal["a", "b", "c"]):
    return {"my_param": my_param}
Chris
  • 18,724
  • 6
  • 46
  • 80