Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add documentation for required query parameters?

Tags:

python

fastapi

I'm trying to create a fastapi API endpoint that relies on HTTP GET parameters, has them documented and uses fastapi's validation capabilities. Consider the following minimal example:

import fastapi

app = fastapi.FastAPI(
)

@app.get("/endpoint")
def example_endpoint(
    par1: int = fastapi.Query(
        None,
        description="example documentation1",
    ),

    par2: int = fastapi.Query(
        None,
        description="example documentation2",
    ),
):
    return {"test": par1 + par2}

This has the documentation support and works over HTTP GET parameters, but doesn't validate them - http://localhost:8000/endpoint?par1=2&par2=3 works fine, but http://localhost:8000/endpoint crashes with an internal server error, instead of notifying the user that a parameter was expected. Is there a way to make par1 and par2 required and keep the documentation feature?

like image 361
d33tah Avatar asked Aug 03 '20 15:08

d33tah


People also ask

Can query parameters be required?

Yes, mandatory parameters can be used in query parameters.

How do you write a parameter query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.


1 Answers

You can use Ellipsis, If you hadn't seen that ... before: it is a special single value that makes query required

from fastapi import Query

Query(...,description="example documentation1")

So in your case answer below can do the job

@app.get("/endpoint")
def example_endpoint(
    par1: int = fastapi.Query(..., description="example documentation1",),
    par2: int = fastapi.Query(..., description="example documentation2",),
):

    if par1 and par2:
        return {"test": par1 + par2}

    raise ValueError("Missing query parameters")

Also you can use example=1

Query(..., description="example documentation2", example=1)
like image 79
Yagiz Degirmenci Avatar answered Oct 19 '22 02:10

Yagiz Degirmenci