Avatar A personal blog about technical things I find useful. Also, random ramblings and rants...

Playing around with FastAPI

Trying out FastAPI for rapid prototyping..

image

FastAPI documentation: https://fastapi.tiangolo.com/tutorial/#run-the-code

Create virtual environment

python -m venv .venv

Activate virtual environment

source venv/bin/activate

Install fastapi

pip install fastapi[all]

To check what packages are installed

pip freeze

Run a sample example.

from fastapi import FastAPI

app = FastAPI()


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

Run the program
```bash
fastapi dev main.py

image

The above code is called a path operation. It has two componenets, functiona nd the decorator.

from fastapi import FastAPI

app = FastAPI()

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

To enable auto-reload server, pass –reload flag

fastapi dev main.py --reload

or

uvicorn main:app --reload
from fastapi import FastAPI

app = FastAPI()

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

@app.get("/posts")
def get_posts():
    return {"data": "This is the post"}

On http://127.0.0.1:8000/posts we get the following output

{
"data": "This is the post"
}

all tags