FastAPI

Complete deployment guide for FastAPI on NStrim

Overview

FastAPI is a modern, high-performance Python web framework for building APIs. It features automatic interactive documentation, type hints validation, and async support out of the box.

Before You Start
Make sure you have your dashboard open - you'll need the Git credentials displayed there. This template includes FastAPI, Uvicorn, SQLAlchemy ORM, PyMySQL driver, Pydantic, and Jinja2 templating.

Quick Start

1

Create Repository from Template

On your dashboard, go to the Tools & Deployment tab. Click the "New Repository" button, select the FastAPI template from the dropdown, enter a repository name and subdomain, then click "Create Repository".

2

Clone Your Repository

git clone https://<git-server>/<username>/<repo-name>.git
cd <repo-name>
3

Install Dependencies

pip install -r requirements.txt
4

Start Development Server

uvicorn app.main:app --reload

Server runs on http://localhost:8000. Interactive API docs at http://localhost:8000/docs.

5

Push Your Changes

git add .
git commit -m "Initial setup"
git push origin main
Every push to Git automatically deploys your application. Check your Module Work URL on the dashboard to see your live site.

Local Development with Docker

If you don't have Python installed locally, you can use Docker to run your FastAPI application.

What is Docker?
Docker creates isolated "containers" with all the software you need (Python, pip) without installing them on your computer.

Running Commands with Docker

# Install dependencies
docker run --rm -v $(pwd):/app -w /app python:3.12 pip install -r requirements.txt

# Run development server
docker run --rm -v $(pwd):/app -w /app -p 8000:8000 python:3.12 sh -c "pip install -r requirements.txt && uvicorn app.main:app --host 0.0.0.0 --reload"

Database Configuration

The NStrim platform provides you with a MySQL/MariaDB database. Configure your connection in the .env file or directly in your database configuration module.

DATABASE_URL=mysql+pymysql://<username>:<password>@db.<session-domain>:3306/<username>
Important
Your database name and username are typically the same as your dashboard username (e.g., student01). Check your dashboard credentials section for exact values.

Project Structure

├── app/
│   ├── main.py                # FastAPI application entry point
│   ├── routers/               # Route modules
│   ├── models/                # SQLAlchemy models
│   ├── schemas/               # Pydantic schemas
│   └── database.py            # Database connection
├── templates/                 # Jinja2 templates
├── static/                    # CSS, JS, images
├── requirements.txt           # Python dependencies
└── Dockerfile                 # Docker config
        

Common Tasks

Creating an API Endpoint

from fastapi import APIRouter

router = APIRouter()

@router.get("/users")
async def get_users():
    return [{"name": "Alice"}, {"name": "Bob"}]

@router.post("/users")
async def create_user(name: str, email: str):
    return {"name": name, "email": email}

Using SQLAlchemy

from sqlalchemy import Column, Integer, String
from app.database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100))
    email = Column(String(255), unique=True)

Pydantic Schema for Validation

from pydantic import BaseModel

class UserCreate(BaseModel):
    name: str
    email: str

class UserResponse(BaseModel):
    id: int
    name: str
    email: str

    class Config:
        from_attributes = True

Useful Commands

uvicorn app.main:app --reload Start dev server with auto-reload
pip install -r requirements.txt Install dependencies
pip freeze > requirements.txt Save current dependencies

Troubleshooting

OperationalError: Can't connect to MySQL server

Cause: Database host is incorrect or not accessible.

Solution: Check that DATABASE_URL matches the database host from your dashboard.

ModuleNotFoundError: No module named 'app'

Solution: Make sure you're running uvicorn from the project root directory and that app/__init__.py exists.

422 Unprocessable Entity

Solution: FastAPI validates request data automatically. Check the response body for details on which fields failed validation. Visit /docs to see the expected request format.

Deployment Workflow

Code Change git push pip install Live!
For more information, visit the official FastAPI Documentation.