# REST API with FastAPI on Windows

A Bitflow Solutions guide. Web version: https://bitflow-solutions.com/en/guias-tecnicas/build-rest-api-fastapi-windows/

## 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

```powershell
winget install -e --id Python.Python.3.12
python --version
pip --version
```

### 2. Project and virtual environment

```powershell
mkdir C:\projects\tasks-api
cd C:\projects\tasks-api
python -m venv .venv
.venv\Scripts\Activate.ps1
```

### 3. Install FastAPI

```powershell
pip install "fastapi[standard]"
pip freeze | Out-File -Encoding utf8 requirements.txt
```

### 4. First API (main.py)

```python
from fastapi import FastAPI

app = FastAPI(title="Tasks API")


@app.get("/")
def home():
    return {"message": "Hello from FastAPI"}
```

### 5. Development server

```powershell
fastapi dev main.py
```

- API: http://127.0.0.1:8000
- Documentation: http://127.0.0.1:8000/docs
- Stop: Ctrl + C

### 6. Model and task endpoints (main.py)

```python
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")
```

### 7. Test from PowerShell

```powershell
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. Automated tests (test_main.py)

```python
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
```

```powershell
pip install pytest
pytest
```

### 9. Container (optional)

Dockerfile (no extension):

```dockerfile
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"]
```

```powershell
docker build -t tasks-api .
docker run -p 8000:80 tasks-api
```

## 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.
