FastAPI?
It's a modern and fast Python web framework. It seems to be popular recently, so I adopted it for business.
Official documentation https://github.com/tiangolo/fastapi
The environment was different depending on the members and the introduction could not proceed smoothly, It's a memo because everyone can now share the same working environment using Docker.
We will proceed according to the official procedure.
It is OK if the file structure is like this in the end. Super simple.
Dockerfile
Install the modules listed in the Installation section of the official documentation. It runs on its own when built, so it's convenient because you don't have to manually search for the required module.
Dockerfile
FROM python:3.7
WORKDIR /var/www/html
RUN pip install fastapi uvicorn
main.py
This is also written with reference to the item of Example. It's an API that returns Hello World objects when the root is accessed.
main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
docker-compose.yaml
It acts as a bridge between Dockerfile
and main.py
.
After installing the Python module using the Dockerfile Refer to the Run it item and hit the command to start the Fast API server.
Here, it is set to start on port 9004.
docker-compose.yaml
version: '3'
services:
app:
container_name: FastAPI
build: ./docker
volumes:
- ./src:/var/www/html
ports:
- "9004:9004"
command: uvicorn main:app --reload --host 0.0.0.0 --port 9004
Start and build the container with docker-compose.
$ docker-compose up --build
Creating network "docker_fastapi_default" with the default driver
Building app
Step 1/3 : FROM python:3.7
---> 879165535a54
Step 2/3 : WORKDIR /var/www/html
---> Using cache
---> 31d5c58e6177
Step 3/3 : RUN pip install fastapi uvicorn
---> Using cache
---> 430430eecf7f
Successfully built 430430eecf7f
Successfully tagged docker_fastapi_app:latest
Creating FastAPI ... done
Attaching to FastAPI
FastAPI | INFO: Uvicorn running on http://0.0.0.0:9004 (Press CTRL+C to quit)
FastAPI | INFO: Started reloader process [1]
FastAPI | INFO: Started server process [7]
FastAPI | INFO: Waiting for application startup.
FastAPI | INFO: Application startup complete.
The required modules have been installed and the Fast API server has started.
Let's access it with the curl command.
$ curl http://localhost:9004
{"Hello":"World"}
Reaction as defined in main.py
!
You can easily set up an API server using FastAPI! It's nice to be able to share the same environment with fewer files using Docker: sparkles:
Since you can also execute shell scripts in Python, It is convenient to implement commands for automatic deployment and do something like "pseudo Jenkins". ~~ Don't say you should use Jenkins ~~
Recommended Posts