Fastapi: [FEATURE] Choices Dropdown Menu in API Documentation

Created on 22 May 2019  路  5Comments  路  Source: tiangolo/fastapi

Feature Request:

It would be nice to document in the API, which what choices are available to the user as a drop-down menu in the UI. It helps prevent such documentation in the description\help of the parameter.

Context
flask_restplus library is able to show choices in its Swagger UI, and is able to handle if incorrect choice is provided as an input by the user.
Selection_005

Preferred Solution:
Would like to see choices parameter added to possibly fastapi.Query class and possibly other classes that handle input from user.
Would be awesome if it was something like this

@api.get('/get_countries')
def get_something(
    choice: str = Query('eu', choices=('eu,'us','cn,'ru'), description='foo bar')
):
    do_something(choice)

Would be nice to see this feature in FastAPI, as I/We would prefer to use FastAPI over flask_restplus.

enhancement

Most helpful comment

Hey @alikhtag, just to let you know, this is available now in the latest versions (actually for some time now).

Here are docs for how to use enums in paths, but the same applies to queries: https://fastapi.tiangolo.com/tutorial/path-params/#predefined-values

Here's your same example:

from fastapi import FastAPI
from enum import Enum


class Country(str, Enum):
    eu = "eu"
    us = "us"
    cn = "cn"
    ru = "ru"


app = FastAPI()


@app.get("/")
def get_something(country: Country = Country.eu):
    return {"country": country.value}

All 5 comments

after some digging it seems it works out of the box:

Imgur

import uvicorn

from fastapi import FastAPI, Query

app = FastAPI()


@app.get('/get_countries')
async def get_countries(_q: str = Query("eu", enum=["eu", "us", "cn", "ru"])):
    return {"selected": _q}


if __name__ == '__main__':
    uvicorn.run("test_swagger_dropdown:app", reload=True)

Thanks @euri10 for your help!

Later I'll add full Enum support for query values too, that way, apart from showing up in Swagger UI, Pydantic validates the values given.

Thanks a lot! This will work! Can't wait for full support!

Hey @alikhtag, just to let you know, this is available now in the latest versions (actually for some time now).

Here are docs for how to use enums in paths, but the same applies to queries: https://fastapi.tiangolo.com/tutorial/path-params/#predefined-values

Here's your same example:

from fastapi import FastAPI
from enum import Enum


class Country(str, Enum):
    eu = "eu"
    us = "us"
    cn = "cn"
    ru = "ru"


app = FastAPI()


@app.get("/")
def get_something(country: Country = Country.eu):
    return {"country": country.value}

@tiangolo
Thanks a lot!

Was this page helpful?
0 / 5 - 0 ratings