Setting Up FastAPI Project Step-by-Step
Introduction
In the previous blog, we learned what FastAPI is and why it’s gaining popularity. Now, let’s get hands-on and set up a FastAPI project from scratch the right way.
A good project setup helps you:
- Write clean code.
- Scale easily.
- Avoid confusion later.
Prerequisites
Before we start, make sure you have:
- Python 3.7+ installed
- Basic knowledge of Python
-
pipinstalled
Step 1: Create a Virtual Environment
Using a virtual environment keeps your dependencies clean.
python -m venv venv
Activate it:
Windows:
venv\Scripts\activate
Mac/Linux:
source venv/bin/activate
Step 2: Install FastAPI & Uvicorn
pip install fastapi uvicorn
- FastAPI → framework
- Uvicorn → ASGI server (runs your app)
Step 3: Basic Project Structure
Here’s a clean and scalable folder structure:
fastapi-project/
│
├── app/
│ ├── main.py
│ ├── routes/
│ ├── models/
│ ├── schemas/
│ └── database/
│
├── venv/
├── requirements.txt
└── README.md
Explanation:
-
main.py→ Entry point of the app -
routes/→ API endpoints -
models/→ Database models -
schemas/→ Pydantic schemas -
database/→ DB connection logic
Step 4: Create Your First App File
Create main.py inside app/:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "FastAPI project is running!"}Step 5: Run the Server
uvicorn app.main:app --reloadBreakdown:
app.main→ folder + fileapp→ FastAPI instance--reload→ auto-restart on changesStep 6: Open in Browser
Once the server is running:
Step 7: Create requirements.txt
Save dependencies: pip freeze > requirements.txt
This helps when deploying or sharing your project.
Best Practices for Setup
1. Always use virtual environments
2. Keep code modular (routes, models, schemas)
3. Use.envfor secrets (later blogs)
4. Follow consistent naming conventions
Common Beginner Mistakes
1. Not using virtual environment
2. Running wrong module path (
main:appvsapp.main:app)3. Forgetting
--reloadduring development4. Mixing all code in one file
Key Takeaways
- FastAPI setup is simple and quick
- Proper structure makes your project scalable
- Uvicorn is required to run FastAPI apps
- Always organize your code from the beginning
Comments
Post a Comment