Python – Creating REST API through FastAPI


In this blog we will focus more on coding than on theory. So, in short we will need python basic data structure knowledge, object-oriented programming knowledge and some idea related to asynchronous web server like uvicorn (as it is utilized). We may use PyTest for unit testing and SQLAlchemy for object relational mapping. We can use any relational database like PostgreSQL or SQLite. We may use Jinja templates for creating web pages. Let’s start coding.

$ mkdir fastapi_app
$ cd fastapi_app
$ python -m venv .venv
$ source ./.venv/bin/activate   # for windows '.\.venv\Scripts\activate
 (venv) $ mkdir backend
 (venv) $ cd backend
 (venv) $ cat > requirements.txt
fastapi
uviconr
 (venv) $ pip install -r requirements.txt
 (venv) $ touch main.py

Open main.py and write following code:

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Now we will run the uvicorn server to start the application:

 (venv) $ uvicorn main:app --reload

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post