In this guide, we’ll understand the process of setting up your FastAPI application. We’ll explore how to structure your project, create environment files, and manage dependencies using tools like poetry. By the end of this section, you’ll have a well-organized foundation for building your API.
Project Structure
A typical FastAPI project structure might look like this:
project_name/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── models.py
│ └── routes.py
├── tests/
├── .gitignore
├── poetry.lock
├── pyproject.toml
appdirectory: This is where your main application code will reside.main.py: The entry point for your application.models.py: Defines data models for your API.routes.py: Contains your path operations and routing logic.testsdirectory: For writing unit and integration tests..gitignore: Specifies files and directories to exclude from Git version control.poetry.lock: Stores dependency versions for reproducibility.pyproject.toml: A configuration file forpoetry.
Creating a Virtual Environment
To isolate your project’s dependencies from your system-wide Python environment, create a virtual environment using poetry:
Bash
poetry init
This will create a poetry.lock file and a pyproject.toml file.
Installing Dependencies
Add FastAPI and other required libraries to your pyproject.toml file:
Ini, TOML
[tool.poetry.dependencies]
python = "^3.7"
fastapi = "^0.95.0"
uvicorn = "^0.18.0"
Then, install them using poetry:
Bash
poetry install
Creating the Main Application File
Create a main.py file in your app directory and import the necessary modules:
Python
from fastapi import FastAPI
app = FastAPI()
Defining Path Operations
Start defining your API’s endpoints in the routes.py file:
Python
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def read_root():
return {"Hello": "World"}
Importing Routes in the Main File
Import the routes.py file in your main.py and include the router:
Python
from app import routes
app.include_router(routes.router)
Running the Application
To start your application, use uvicorn:
Bash
poetry run uvicorn app.main:app --reload
This will start the application on the default host and port.
