Published on

Build a REST API with Python and Mysql - Fastapi Version(draft)

Authors
  • avatar
    Name
    Lif
    Twitter

Actually it's a little difficult to move my story from medium to here...

Representational state transfer (REST) is a software architectural style that describes a uniform interface between physically separate components. Generally REST describes a interface. In web development REST allows content to be rendered when it's required, often referred to as Dynamicd Content. In this story we will build a REST api with Fastapi.

You can find the complete source code in this repository.

Prerequisites The following steps in this story require Python experience. We will also be needing the following: Mongodb installed Postman or any API testing application of your choice

Get started Installing FastAPI First, we should create a folder, then we need a virtual environment. makedir fastapp && cd fastapp python3 -m venv venv . ./venv/bin/activate Now that we have a virtual environment created and activated, we can finally install FastAPI in it: (venv) $ pip install fastapi[all]
that also includes uvicorn, which we can use as the server that runs our code. A "Hello World" FastAPI Application Let's create a package called app to start our first application. vim main.app # or just create a file named main.py

The snippet above does the following: Import the FastAPI package. Initialize an FastAPI instance as app . Use the @app.get decorator to route to / path and invoke the root function Use a async function to return message

The @app.get('/') lines above the function are decorators, a unique feature of the Python language. In this case, the @app.get decorator creates an association between the URL and the function. After then, we can use uvicorn to start our server. $ uvicorn main:app --reload here we get output INFO: Started server process [11386] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) Open our browser at http://127.0.0.1:8000 and we will get the correct response. Struct our project Before we creat a lot of py files, we should can design the structure first. Whit a good structure, we can get good names of directories so that their purpose is clear. Keeping all project files (including virtualenv) in one place, so we can easily copy, move, archive, remove the whole project, or estimate disk space usage. Create some folder just like the picture above.