FastAPI Tutorial Memo Part 1

Introduction

FastAPI Souce: https://github.com/tiangolo/fastapi FastAPI Document: https://fastapi.tiangolo.com

Intro & First Step FastAPI tutorial notes. Basically, I refer to the official tutorial of Fast API, but I omit some parts or change the order for my own learning. Please refer to the official documentation for the correct and detailed information.

Since I am a beginner of Web & Python and rely on Google and DeepL for translation, I would appreciate it if you could point out any mistakes.

Development environment

Ubuntu 20.04 LTS Python 3.8.2 pipenv 2018.11.26

Target

  1. [Install FastAPI](#Install FastAPI)
  2. [Start Server](# Start Server)
  3. [Check Swagger UI](# Swagger-Check UI)
  4. [Check Code](#Check Code)

What is FastAPI

FastAPI is a fast, lightweight and modern web framework for building APIs based on Python type hints. It conforms to OpenAPI (Swagger), which is an open standard of API, and JSON schema. Please check the Official Document for details.

procedure

FastAPI installation

Install FastAPI using pip. You can install all the dependencies and features used by the Fast API with the following command, so let's install with this command for the time being in the development environment. You can also install ʻuvicorn`, which is used as a server, at once.

$ pip install fastapi[all]

████████████████████████████████████████ 100%

Let's check it with python's interactive shell.

$ python
Python 3.8.2 (default, Apr 21 2020, 18:13:10) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> from fastapi import FastAPI
>>> 

If no error is displayed, the installation is successful. Also, since I use pipenv in my environment, I installed it with pipenv install fastapi [all], but there is no problem so far.

I will omit it here, but it is also possible to install fastapi and ʻuvicorn` separately.

Start the server

Now that you have installed FastAPI, let's start the server right away.

First, write a simple Fast API code in the main.py file. (The code is basically taken from the official documentation. Please check Reference.)

main.py


from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

After saving the code, start the server with the following command.

$ uvicorn main:app --reload

If the following display is output, the server is running.


INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.

The output has the line ʻINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL + C to quit) `. It seems to tell me the URL (http://127.0.0.1:8000) where the app is running on the local machine and how to stop the server (Control key + C).

Let's display http://127.0.0.1:8000 in the browser at once. You should see the return value of the root function in main.py (return {"message ":" Hello World "}).

qiita_1_1 2020-07-12 17-03-29.png

About ʻuvicorn main: app --reload`

--Refer to the main.py file (= Python module) for main --The file name can be set freely. Let's change it to control.py etc. In that case, you also need to change the command. --ʻApp refers to the object created by ʻapp = FastAPI in the main.py file ――This can be set freely as well as the file name. ---- reload is an option to restart the server every time the code changes --This option is recommended for use only in the development environment.

Check Swagger UI

FastAPI is OpenAPI compliant and will automatically generate interactive API documentation with the Swagger UI. Visit http://127.0.0.1:8000/docs to check.

qiita_1_2 2020-07-12 17-15-44.png

You can also check the documentation by ReDoc by visiting http://127.0.0.1:8000/redoc.

Check the code

Let's check the contents of main.py. This code is the basic code for the Fast API.

Fast API import

First, import the FastAPI class. This FastAPI provides all the functionality of the API you create.

from fastapi import FastAPI

Create an instance

Next, create a variable that will be an instance of the Fast API. This variable is the entity of the Fast API.

from fastapi import FastAPI

app = FastAPI()

The instance variable ʻapp created here corresponds to the option main: app of the ʻuvicorn command. If the file name is control.py and the instance variable ismy_instance = FastAPI (), the ʻuvicorn` command will be as follows.

$ uvicorn control:my_instance --reload

INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Creating a Path Operation

** Path ** here refers to the part of the URL that starts with / after the domain name and port name. In the case of the URL https://example.com/items/foo, the part / items / foo corresponds to the Path in the Fast API.

You can also think of Path as having the same meaning as the general ** endpoint ** and ** route **. In FastAPI, the role of ** Path ** is "separation of" concerns "(interest) and" resource "(resource) in API construction". Does that mean to divide the program into units of interest (purpose, what you want to do) and resources (resources, what you want to use)? Please let me know if you have any details.

Also, Path Operation ** Operation ** is synonymous with HTTP method. The main methods used are:

--POST: Creating data --GET: Read data --PUT: Data update --DELETE: Delete data

HTTP can communicate with each path on the web server by using these methods. When building the API, we use these HTTP methods to perform certain actions.

The HTTP method is called ** operation ** in OpenAPI, and the term ** operation ** is used in FastAPI accordingly.

Let's define a ** path operation decorator ** using instance variables.

from fastapi import FastAPI

app = FastAPI()


@app.get("/")

The decorator function @ app.get ("/ ") allows the Fast API to handle the following requests using the function directly below.

-** path ** is / and -Use get method for ** operation **

See other articles for decorator functions. It's used here to tell the Fast API that the function directly under the decorator function corresponds to ** path/**. Also, such a decorator function is called ** path operation decorator **.

You can also use operations other than get as shown below.

Definition of path operation function

At the end of checking the code, define the path manipulation function and set the return value.

The path operation decorator @ app.get ("/") allowed us to define an HTTP request to start processing. Next, define the function to do the processing just below the decorator.

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():

The path manipulation function used here (ʻasync def root (): ) is no different from a regular Python function. The Fast API calls this function every time the client sends a request to URL / with getʻoperation and the server receives it. (I also wanted this function to be called when I accessed http://127.0.0.1:8000.)

You can also define a regular function instead of ʻasync def`.

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def root():
    return {"message": "Hello World"}

For ʻasync` (asynchronous processing), refer to the official document of here.

After that, set the return value with return, and the confirmation of the first code will be completed.

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

Regarding the return value, you can set the return value with types such as dict and list for multiple values and str and ʻintfor singular values. Alternatively, it is possible to return aPydantic` model. In addition to the above, there are many objects and models (including ORM) that are automatically converted to JSON. Please check it out.

Closing about OpenAPI

This time, among the official tutorials of Fast API, Intro and First Steps I picked it up. Finally, I will cover the description of OpenAPI and Schema.

What is OpenAPI?

OpenAPI is a format for writing REST API, and Swagger is an open source toolset to be used when writing OpenAPI. It was briefly summarized in the following article.

-OpenAPI (Swagger) Super Introduction

In FastAPI, API definitions are OpenAPI compliant, and all APIs generate a "schema".

What is a schema?

A "schema" is some definition or description. It refers to an abstract concept, not implemented code.

API schema

When considering the "schema" in the API, OpenAPI is a specification that defines how to define the schema of the created API.

This schema definition includes the path to the API and the parameters that the API may get.

Data schema

The word "schema" can also refer to some form of data, such as JSON content.

In that case, it means the JSON attributes and the data types they have.

Relationship between OpenAPI and JSON Schema

OpenAPI defines the "API schema" of the created API, which uses the JSON Schema standard "JSON Schema" to define the data sent and received by the API (or any other "schema"). It contains.

FastAPI uses the OpenAPI schema to run two types of interactive document systems (Swagger UI, ReDoc).

reference

FastAPI Official Tutorial Intro FastAPI Official Tutorial First Steps

Recommended Posts

FastAPI Tutorial Memo Part 1
FastAPI Tutorial Memo Part 3 Query Parameters
FastAPI Tutorial Memo Part 2 Path Parameters
django tutorial memo
List memo writing part 2
Python OpenCV tutorial memo
Python basic memo --Part 1
pyramid tutorial memo (bank account)
Linux standard textbook memo 1 part 2
Python Basic Grammar Memo (Part 1)
Linux standard textbook memo part 6
[PyTorch Tutorial ⑤] Learning PyTorch with Examples (Part 2)
[For memo] Linux Part 1 vi editor
[PyTorch Tutorial ⑤] Learning PyTorch with Examples (Part 1)
Mastodon Bot Creation Memo: Part 4 Summary
How to use FastAPI ① Tutorial --User Guide
Memo about Sphinx Part 1 (Creating a project)
Environment construction for MXNet tutorial (gluon part)
"Deep Learning from scratch" Self-study memo (Part 12) Deep learning