Getting Started with Fast API and Docker

Fast API

Fast API is a web framework for building APIs with Python 3.6+ based on standard Python type hints. It is one of the fastest python frameworks available and very easy to learn and use.

Installation of fastapi on windows

pip install fastapi
 pip install uvicorn

Installation on MacOS and Linux

%pip install fastapi
 %pip install uvicorn

An Example

Create a python file and save as myapp.py with:

from fastapi importFastAPI
 app=FastAPI()
 @app.get("/")
 async def greetings():
     return "Helloo my viewer. Really proud of you!!"

Then run the server with the command:

uvicorn myapp:app --reload

The server is open when the following info shows up:

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.

Then open your browser at http://127.0.0.1:8000
You will see the JSON response as:

"Helloo my viewer. Really proud of you!!"

To see the automatic interactive API documentation add '/docs' to your url i.e (http://127.0.0.1.8000/docs):
Image description

Docker

Docker is an open source platform for building ,deploying and managing containerized applications.
Docker file is a text document that contains all the commands a user could call on the command line to assemble an image
Docker image is a read-only, inert template that comes with instructions for deploying containers.
Docker container is a virtualized runtime environment that provides isolation capabilities for separating the execution of applications from the underpinning system.

In Python requirements.txt file is a type of file that usually stores information about all the libraries, modules and packages in itself that are used while developing a particular project.

Creating a requirements.txt file:

pip freeze > requirements.txt

Docker python application:

we need to create a directory

cmd docker-python-app

Then enter into the directory and create a Dockerfile with:

FROM python:3.6
COPY . /src  
CMD ["python", "/src/index.py"]

Then create a python file(This python file(index.py) will be executed in the docker container.) with:

print("Hello Docker!!")

creating a docker image for the python application:

$ docker build -t python-app

Then run docker with:

$ docker run python-app

Hope this was useful, please feel free to leave your comments below.

20