Fastapi: [QUESTION] How to specify json data input in docs for request?

Created on 28 Feb 2020  路  5Comments  路  Source: tiangolo/fastapi

Question

How can I make my Input parameters show up in the swagger docs for a JSON request? I make requests like this ...

curl 'http://127.0.0.1:5000/predict' -H "Content-Type: application/json" --data '{"data": ["string1", "string2"]}'

from fastapi import FastAPI
from starlette.requests import Request
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Prediction(BaseModel):
    term: str
    label: str
    score: str

class Output(BaseModel):
    success: bool
    prediction: List[Prediction] = []

# .. this is probably wrong.
class Input(Request, BaseModel): 
    data: List[str] = []

@app.post('/predict', response_model=Output)
async def predict(request: Input):

    data = Output(success=False)

    try:
        params = await request.json()
    except Exception as e:
        print(e)
    ...
    data.success = True
    return data

Swagger docs without input parameters

Screen Shot 2020-02-28 at 9 49 08 AM

I would like this to show the input schema so the user knows they're supposed to POST with {"data": [list of strings])

question

All 5 comments

Shouldn't this

class Input(Request, BaseModel): 
    data: List[str] = []

be this

class Input(BaseModel): 
    data: List[str] = []

I don't think you need Request in your input model.

Then the await request.json() won't work since request is just Input and not a starlette.requests.Request

@Shane-Neeley
You don't need to await request.json(). You can take @iishyfishyy's advice and remove the Request inheritance:

class Input(BaseModel):
    data: List[str] = []
...
async def predict(request: Input):
    ...
    # Prints ['string1', 'string2'] in your example
    print(request.data)
    ...

fastapi will take care of deserializing the body into request for you, so there's no need to await request.json(). Also note that it will show up as a "Request body." "Parameters" is for url (query) params.
Screen Shot 2020-03-03 at 8 23 09 PM

That did the trick. Thank you.

Thanks for the help here everyone! :cake:

Thanks @Shane-Neeley for reporting back and closing the issue :+1:

Was this page helpful?
0 / 5 - 0 ratings