» Python: Building Event-Driven Microservices with Kafka » 2. Producer: Web Service » 2.2 FastAPI Web Server

FastAPI Web Server

Create your project folder named lr_event_driven_py.

Create a Virtual Environment

It's a good practice to use a virtual environment to isolate your project dependencies. You can create a virtual environment using venv module (built-in to Python 3).

python3 -m venv lrFastAPIEnv

Caution:
If you're using git or any other version control system, remember to ignore the virtual environment folder.
e.g. in .gitignore:

+
+lrFastAPIEnv/

Activate Virtual Environment

Activate the virtual environment. This step is platform-specific.

On Windows:

lrFastAPIEnv\Scripts\activate

On macOS and Linux:

source lrFastAPIEnv/bin/activate

Manage dependencies

Create a file named requirements.txt in the root directory of your project. This file will list all the dependencies of your project along with their versions. You can generate this file automatically by using the pip freeze command:

pip3 freeze > requirements.txt

If your virtual environment is set up properly, you should get a empty file named requirements.txt.

Installation

Install FastAPI framework:

pip3 install fastapi

You will also need an ASGI server, for production such as Uvicorn or Hypercorn.

pip3 install "uvicorn[standard]"

After installation, update requirements.txt:

pip3 freeze > requirements.txt

This command updates the requirements.txt. It should be something similar to this:

annotated-types==0.6.0
anyio==4.3.0
click==8.1.7
fastapi==0.110.1
h11==0.14.0
httptools==0.6.1
idna==3.6
pydantic==2.6.4
pydantic_core==2.16.3
python-dotenv==1.0.1
PyYAML==6.0.1
sniffio==1.3.1
starlette==0.37.2
typing_extensions==4.11.0
uvicorn==0.29.0
uvloop==0.19.0
watchfiles==0.21.0
websockets==12.0

Create templates

Create a folder named templates, and move index.html into the folder.

Tune its title:

- <h1 class="text-4xl font-bold">LiteRank Book Store</h1>
+ <h1 class="text-4xl font-bold">{{ title }}</h1>

{{ title }} is a template syntax used by the Jinja templating engine. You can use any template engine you want with FastAPI. A common choice is Jinja2, the same one used by Flask and other tools.

Install Jinja2

pip3 install Jinja2

Remember to update requirements.txt.

Create main.py:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
async def index_page(request: Request):
    return templates.TemplateResponse(
        name="index.html", context={"request": request, "title": "LiteRank Book Store"}
    )

Run the program like this:

uvicorn main:app --reload

The command uvicorn main:app refers to:

  • main: the file main.py (the Python "module").
  • app: the object created inside of main.py with the line app = FastAPI().
  • --reload: make the server restart after code changes. Only do this for development.

You will get result lines like below:

INFO:     Will watch for changes in these directories: ['.../projects/lr_event_driven_py']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [22891] using watchgod
INFO:     Started server process [22893]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Your web server is runnong on port 8000 now.

Try visiting the URL http://localhost:8000/ in your browser. It should display the webpage we designed in the previous section.

PrevNext