FastAPI Server
Create your project folder named lr_fulltext_search_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.2
h11==0.14.0
httptools==0.6.1
idna==3.7
pydantic==2.7.0
pydantic_core==2.18.1
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 main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def welcome():
return {"status": "ok"}
Run the program like this:
uvicorn main:app --reload
The command uvicorn main:app
refers to:
main
: the filemain.py
(the Python "module").app
: the object created inside ofmain.py
with the lineapp = 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_fulltext_search_py']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [37917] using watchgod
INFO: Started server process [37919]
INFO: Waiting for application startup.
INFO: Application startup complete.
Your server is runnong on port 8000 now.
Try visiting the URL http://localhost:8000/ in your browser or curl
. It should display the json:
{
"status": "ok"
}
Data model: Book
Data models represent the structure of the data that the API deals with.
Create domain/model/book.py:
Folder structures like
domain/model/...
is using 4 Layers Architecture Pattern, read more here.
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
published_at: str
content: str