In this guide we build a REST API from scratch on Windows with FastAPI, the Python framework for APIs: a task service with endpoints to list, create and retrieve tasks, automatic documentation, tests and a container ready to deploy. Every command is typed in PowerShell, and you have the same steps in the README.md on the left.
What you’ll learn
- Set up Python on Windows and a virtual environment for the project.
- Build a REST API with FastAPI and data models validated with Pydantic.
- Use the interactive documentation that FastAPI generates on its own (
/docs). - Test the API from PowerShell and with automated tests (pytest).
- Package it in a Docker container ready to deploy.
Prerequisites
- Windows 10 or 11 with PowerShell (it comes preinstalled: search for it in the Start menu).
- Python 3.10 or later (step 1 installs it if you don’t have it).
- Visual Studio Code with Microsoft’s Python extension, or the editor of your choice.
- Basic knowledge of Python and of what a REST API is (GET, POST, JSON).
- Docker Desktop with WSL 2, only for the last step (optional).
Step by step
1. Install Python and check it works
Open PowerShell and install Python with winget, the Windows package manager:
winget install -e --id Python.Python.3.12
You can also download it from python.org; in that case, tick “Add python.exe to PATH” on the installer’s first screen. Close and reopen PowerShell and check that it responds:
python --version
pip --version
2. Create the project and its virtual environment
The virtual environment isolates this project’s dependencies from the rest of the machine. Once it is activated, the PowerShell prompt starts with (.venv).
mkdir C:\projects\tasks-api
cd C:\projects\tasks-api
python -m venv .venv
.venv\Scripts\Activate.ps1
3. Install FastAPI
The fastapi[standard] package includes the server (Uvicorn), the fastapi command-line tool and everything needed for testing. Save the dependencies to requirements.txt, in UTF-8 so that Docker can read it too:
pip install "fastapi[standard]"
pip freeze | Out-File -Encoding utf8 requirements.txt
4. Write your first API
Open the folder in Visual Studio Code and, if it asks which Python interpreter to use, choose the one in .venv:
code .
Create the main.py file:
from fastapi import FastAPI
app = FastAPI(title="Tasks API")
@app.get("/")
def home():
return {"message": "Hello from FastAPI"}
5. Start the development server
In PowerShell, with the virtual environment activated:
fastapi dev main.py
Open http://127.0.0.1:8000 and you will see the message in JSON. At http://127.0.0.1:8000/docs you have the interactive documentation (Swagger UI), generated from the code, where you can try out each endpoint. The server reloads automatically when you save; to stop it, press Ctrl + C.
6. Add a model and the task endpoints
With Pydantic you define the shape of the data: FastAPI validates every request, returns a 422 error if it doesn’t match and documents the contract in /docs. Replace main.py with:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="Tasks API")
class NewTask(BaseModel):
title: str
done: bool = False
class Task(NewTask):
id: int
tasks: list[Task] = []
@app.get("/")
def home():
return {"message": "Hello from FastAPI"}
@app.get("/tasks")
def list_tasks() -> list[Task]:
return tasks
@app.post("/tasks", status_code=201)
def create_task(new: NewTask) -> Task:
task = Task(id=len(tasks) + 1, **new.model_dump())
tasks.append(task)
return task
@app.get("/tasks/{task_id}")
def get_task(task_id: int) -> Task:
for task in tasks:
if task.id == task_id:
return task
raise HTTPException(status_code=404, detail="Task not found")
The tasks are kept in memory to keep the example simple: they are lost when the server restarts. In a real project they would go to a database.
7. Test the API from PowerShell
Open a second PowerShell window (the first one is still running the server) and use Invoke-RestMethod:
Invoke-RestMethod -Method Post -Uri http://127.0.0.1:8000/tasks -ContentType "application/json" -Body '{"title": "First task"}'
Invoke-RestMethod http://127.0.0.1:8000/tasks
Invoke-RestMethod http://127.0.0.1:8000/tasks/1
8. Add automated tests
Create test_main.py next to main.py:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_and_get_task():
response = client.post("/tasks", json={"title": "First task"})
assert response.status_code == 201
task = response.json()
response = client.get(f"/tasks/{task['id']}")
assert response.status_code == 200
assert response.json()["title"] == "First task"
def test_task_that_does_not_exist():
assert client.get("/tasks/999").status_code == 404
Install pytest and run the tests with the virtual environment activated:
pip install pytest
pytest
9. Package it in a container (optional)
With Docker Desktop open, create a file called Dockerfile, with no extension, in the project folder:
FROM python:3.12-slim
WORKDIR /code
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
CMD ["fastapi", "run", "main.py", "--port", "80"]
Build the image and run it:
docker build -t tasks-api .
docker run -p 8000:80 tasks-api
The API is available at http://127.0.0.1:8000, ready to deploy on Kubernetes, Azure Container Apps or any container platform.
Common errors
“python” opens the Microsoft Store
Windows ships with aliases that send you to the Store. Turn them off in Settings → Apps → Advanced app settings → App execution aliases (python.exe and python3.exe) and reopen PowerShell.
“Running scripts is disabled on this system”
This appears when you activate the virtual environment. Allow local scripts for your user only and run .venv\Scripts\Activate.ps1 again:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
“fastapi” is not recognised as a command
The virtual environment is not activated (the prompt doesn’t start with (.venv)) or FastAPI was installed outside it. Activate it and repeat step 3.
Port 8000 is already in use
Another application is using it. Start on a different port and use that address:
fastapi dev main.py --port 8001
“curl” doesn’t work like in examples on the internet
In Windows PowerShell, curl is an alias for Invoke-WebRequest and doesn’t understand curl’s options. Use Invoke-RestMethod as in step 7, or curl.exe if you want the real curl.
The API responds 422 Unprocessable Entity
The request body doesn’t match the model: title is missing, has a different type or the JSON is not valid. The response tells you which field fails; check it in /docs.
Docker can’t read requirements.txt
If you created it with > in Windows PowerShell, the file ends up in UTF-16. Generate it again with Out-File -Encoding utf8 as in step 3.
Next steps
- Store the tasks in a database, for example PostgreSQL with SQLModel.
- Protect the endpoints with OAuth 2.0 and JWT tokens (see the OpenAPI 3 contract with OAuth and API Key guide).
- Publish it behind an API Gateway with quotas and versioned contracts.
- Automate testing and deployment with a CI/CD pipeline.