[PYTHON] For the time being using FastAPI, I want to display how to use API like that on swagger

Overview

Anyway, for the time being, define the form of the response from the API on the swagger screen of the Fast API, Articles for people who want to see sample responses.

I was like that, but I couldn't find such an article or blog, For the time being, I went through the fastapi official tutorial. I wrote it in the hope that it would help someone with the same purpose.

Premise

――Suppose that this type of data is returned as a response.

{
    "Special_choco1": {
      "Milk": "many",
      "Quantity": 5,
      "Cacao": "a little"
    },
    "Store":[
      {
        "Tokyo": "sibuya",
        "Hokkaido": "sapporo",
        "Osaka": "nanba"
      }
    ]
}

--FastAPI version is 0.52.0

--Write in main.py Write in a file that writes app = FastAPI ().

-I'm sure there is another better way to write it.

First, define the shape of the response

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

class choco_model(BaseModel):
    Milk: str
    Quantity: int
    Cacao: str

class Store_model(BaseModel):
    Tokyo: str
    Hokkaido: str
    Osaka: str

class Special_choco(BaseModel):
    Special_choco1: choco_model
    Store: List[Store_model]

app = FastAPI()

@app.get("/api/v1/chocolate/{name}")
async def making_choco(name: str):
    return #Omitted. An image of writing something that the JSON described in the premise changes.

Display the model defined in Example Value

Specify the model you want to define in response_model at the decorator. Then, it will be displayed in the Swagger's Example Value.

#Omission)

app = FastAPI()

@app.get("/api/v1/chocolate/{name}", response_model=Special_choco)
async def making_choco(name: str):
    return #Omitted. An image of writing something that the JSON described in the premise changes.

Like this. スクリーンショット 2020-04-05 21.59.48.png

Display Example Value more specifically.

To display not only the type and data structure, but also what kind of value is returned Describe the data you want to display in the definition part in class Config as follows. Then, the concrete value will be displayed in the example value column.

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List


class choco_model(BaseModel):
    Milk: str
    Quantity: int
    Cacao: str
    class Config:
        schema_extra = {
            "example": {
                "Milk": "very lot",
                "Quantity": 10,
                "Cacao": "many",
            }
        }

class Store_model(BaseModel):
    Tokyo: str
    Hokkaido: str
    Osaka: str

    class Config:
        schema_extra = {
            "example": {
                "Tokyo": "shibuya",
                "Hokkaido": "sapporo",
                "Osaka": "nishinari",
            }
        }
#Omission

It is displayed as follows. スクリーンショット 2020-04-05 22.08.35.png

Finally

The fastapi official tutorial has a lot of volume, but it is good to do it.

Recommended Posts

For the time being using FastAPI, I want to display how to use API like that on swagger
I want to use the Ubuntu desktop environment on Android for the time being (Termux version)
I want to use Ubuntu's desktop environment on Android for the time being (Termux version-Japanese input in desktop environment)
I want to move selenium for the time being [for mac]
I want to create a Dockerfile for the time being.
How to use the Slack API using Python to delete messages that have passed a certain period of time for a specific user on a specific channel
[For those who want to use TPU] I tried using the Tensorflow Object Detection API 2
For the time being, I want to convert files with ffmpeg !!
How to use MkDocs for the first time
I will try to summarize the links that seem to be useful for the time being
[For beginners] How to display maps and search boxes using the GoogleMap Javascript API
I tried running PIFuHD on Windows for the time being
I didn't know how to use the [python] for statement
For the time being, try using the docomo chat dialogue API
I don't tweet, but I want to use tweepy: just display the search results on the console
I want to use shortcut translation like DeepL app on Linux
I want to use Linux on mac
I want to display the progress bar
I want to display an image on Jupyter Notebook using OpenCV (mac)
[Hi Py (Part 1)] I want to make something for the time being, so first set a goal.
I tried using scrapy for the first time
I checked the library for using the Gracenote API
python I don't know how to get the printer name that I usually use.
I want to use Python in the environment of pyenv + pipenv on Windows 10
Use logger with Python for the time being
Run yolov4 "for the time being" on windows
I played with Floydhub for the time being
I want to use PyTorch to generate something like the lyrics of Japari Park
How to use the Google Cloud Translation API
Try using LINE Notify for the time being
How to use the NHK program guide API
Looking back on the machine learning competition that I worked on for the first time
I thought I could make a nice gitignore editor, so I tried to make something like MVP for the time being
I want to use the activation function Mish
Library for "I want to do that" of data science on Jupyter Notebook
I want to display the progress in Python!
[Writing] I want to display the variables used in the program on the server side in real time on the browser and update them.
How to use pip, a package management system that is indispensable for using Python
I tried to understand how to use Pandas and multicollinearity based on the Affairs dataset.
I tried to score the syntax that was too humorous and humorous using the COTOHA API.
[Pyhton] I want to solve the problem that tkinter does not work on MacOS11
I don't know what HEIC is. But for the time being, let's use PNG!
I want to take a screenshot of the site on Docker using any font
I want to create a lunch database [EP1] Django study for the first time
I want to create a lunch database [EP1-4] Django study for the first time
Use Twitter API to reduce the time taken by Twitter (create a highlighting (like) timeline)
[BigQuery] How to use BigQuery API for Python -Table creation-
I tried Python on Mac for the first time.
Flow memo to move LOCUST for the time being
I tried python on heroku for the first time
I will install Arch Linux for the time being.
Next to Excel, for the time being, jupyter notebook
I want to use OpenJDK 11 on Ubuntu Linux 18.04 LTS / 18.10
I want to automate ssh using the expect command!
I want to restart CentOS 8 on time every day.
I want to use the R dataset in python
"Stop committing Japanese files to git on Mac> <" For the time being, I wrote a script to search for incompatible Japanese files on Mac and Linux.
I want to absorb the difference between the for statement on the Python + numpy matrix and the Julia for statement
How to solve the problem that video content cannot be played on Firefox for Linux
[Selenium] I want to display the browser by hitting the driver on the host OS from WSL
I don't want to search for high para because it is IQ1 (how to use lightgbm_tuner)