---
title: "Cara Deploy FastAPI ke Helipod: Python API Production-Ready dalam Menit"
url: "https://helipod.io/blog/cara-deploy-fastapi-ke-helipod"
date: "2026-05-04"
updated: "2026-05-04"
author: "Tim Helipod"
tags: ["fastapi", "python", "api", "tutorial", "deployment", "uvicorn"]
excerpt: "Cara deploy FastAPI ke Helipod dengan deteksi otomatis dan uvicorn, cocok untuk REST API, ML model serving, hingga async backend."
---

# Cara Deploy FastAPI ke Helipod: Python API Production-Ready dalam Menit

FastAPI adalah framework Python tercepat untuk membangun REST API, dengan type hints, auto-generated docs (Swagger UI), dan performa async yang mendekati Node.js. Tidak heran FastAPI jadi pilihan utama untuk backend API, ML model serving, dan microservice modern.

Deploy FastAPI ke production dengan Helipod semudah push kode ke GitHub. **Helipack** mendeteksi FastAPI dari `requirements.txt` atau `pyproject.toml`, install dependencies, dan jalankan dengan `uvicorn`: server async yang paling cocok untuk FastAPI.

## Yang Kamu Butuhkan

- Akun Helipod (daftar gratis di [helipod.io](https://helipod.io))
- Repository FastAPI di GitHub atau GitLab
- Python 3.10+

## Persiapan Project FastAPI

### 1. Struktur Project Minimal

```
myproject/
├── main.py          # atau app/main.py
├── requirements.txt
└── .env.example
```

### 2. File main.py

```python
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: koneksi ke database, dll
    yield
    # Shutdown: cleanup

app = FastAPI(
    title="My API",
    description="API keren dengan FastAPI",
    version="1.0.0",
    lifespan=lifespan,
)

@app.get("/")
async def root():
    return {"message": "Hello from Helipod!"}

@app.get("/health")
async def health():
    return {"status": "ok"}
```

### 3. requirements.txt

```txt
fastapi>=0.110.0
uvicorn[standard]>=0.29.0
pydantic>=2.0
pydantic-settings>=2.0

# Database
sqlalchemy>=2.0
asyncpg>=0.29.0     # untuk async PostgreSQL
alembic>=1.13.0     # untuk migrasi

# Opsional
python-dotenv>=1.0
httpx>=0.27.0       # untuk HTTP client async
```

> **Penting:** Gunakan `uvicorn[standard]` (bukan `uvicorn` biasa) untuk mendapat `uvloop` dan `httptools` yang jauh lebih cepat.

### 4. Konfigurasi Settings dengan Pydantic

Praktik terbaik untuk FastAPI adalah menggunakan `pydantic-settings` untuk konfigurasi:

```python
# config.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str = "sqlite+aiosqlite:///./test.db"
    secret_key: str = "your-secret-key"
    debug: bool = False
    port: int = 8000
    
    class Config:
        env_file = ".env"

settings = Settings()
```

## Langkah 1: Tambahkan Database Service (Opsional)

Jika butuh PostgreSQL, tambahkan service PostgreSQL dulu di canvas Helipod sebelum deploy FastAPI. Catat nama service-nya.

## Langkah 2: Connect Repository

Login ke dashboard Helipod, klik **New Project**, pilih repository FastAPI. Helipack mendeteksi Python + FastAPI dari `requirements.txt`.

## Langkah 3: Set Environment Variables

Buka tab **Variables**:

```env
DEBUG=false
SECRET_KEY=your-super-secret-key-ganti-ini

# Database async PostgreSQL
DATABASE_URL=postgresql+asyncpg://postgres:password@nama-service-postgres:5432/mydb

# Atau sync (tanpa async):
DATABASE_URL=postgresql://postgres:password@nama-service-postgres:5432/mydb

# CORS
ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com

# Opsional
API_KEY=your-api-key
ENVIRONMENT=production
```

> **asyncpg vs psycopg2:** Untuk FastAPI async, gunakan `asyncpg` dengan prefix `postgresql+asyncpg://`. Untuk sync (lebih simpel), gunakan `psycopg2-binary` dengan `postgresql://`.

## Langkah 4: Deploy

Klik **Deploy**. Helipack akan:

1. Detect Python + FastAPI
2. Install dependencies dari `requirements.txt`
3. Build Docker image
4. Deploy dengan `uvicorn main:app --host 0.0.0.0 --port 8000`

## Dockerfile yang Dihasilkan Helipack

```dockerfile
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS base
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1

RUN apt-get update && apt-get install -y --no-install-recommends \
    curl build-essential libffi-dev libssl-dev \
    && rm -rf /var/lib/apt/lists/*

FROM base AS deps
WORKDIR /app
COPY requirements.txt ./
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --no-cache-dir -r requirements.txt

FROM base AS runner
WORKDIR /app

COPY --from=deps /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY --from=deps /usr/local/bin /usr/local/bin

COPY . .

RUN useradd --no-create-home --shell /bin/false appuser && \
    chown -R appuser:appuser /app
USER appuser

EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```

## Menggunakan uv untuk Install Lebih Cepat

`uv` adalah package manager Python ultra-cepat (10-100x lebih cepat dari pip). Helipack mendukungnya otomatis jika ada `uv.lock`:

```toml
# pyproject.toml
[project]
name = "myapi"
requires-python = ">=3.12"
dependencies = [
    "fastapi>=0.110.0",
    "uvicorn[standard]>=0.29.0",
    "pydantic>=2.0",
    "asyncpg>=0.29.0",
    "sqlalchemy>=2.0",
    "alembic>=1.13.0",
]
```

```bash
# Generate lock file
uv lock
git add uv.lock pyproject.toml
```

Helipack akan detect `uv.lock` dan menggunakan `uv sync --frozen --no-dev`: jauh lebih cepat.

## Konfigurasi Lanjutan

### Custom Start Command

Override start command di `helipack.json` untuk production-grade setup:

```json
{
  "run": {
    "port": 8000,
    "command": "uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 --loop uvloop"
  },
  "health": {
    "path": "/health",
    "duration": 15
  }
}
```

> **Workers:** Untuk FastAPI async dengan `--workers > 1`, pastikan kamu tidak menggunakan shared in-memory state antar workers. Gunakan Redis atau database untuk state sharing.

### Jalankan Alembic Migrasi Otomatis

```json
{
  "run": {
    "port": 8000,
    "before": "alembic upgrade head",
    "command": "uvicorn main:app --host 0.0.0.0 --port 8000 --workers 2"
  }
}
```

### Multi-file Project (App sebagai Package)

Jika menggunakan struktur `app/main.py`:

```json
{
  "run": {
    "command": "uvicorn app.main:app --host 0.0.0.0 --port 8000"
  }
}
```

## FastAPI dengan SQLAlchemy Async

Setup database async yang proper untuk production:

```python
# database.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
import os

engine = create_async_engine(
    os.environ["DATABASE_URL"],
    echo=False,
    pool_size=10,
    max_overflow=20,
)

AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)

class Base(DeclarativeBase):
    pass

# Dependency
async def get_db():
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
```

## Akses Swagger UI

Setelah deploy, FastAPI otomatis menyediakan dokumentasi interaktif di:
- **Swagger UI:** `https://nama-project.helipod.app/docs`
- **ReDoc:** `https://nama-project.helipod.app/redoc`

Matikan di production jika tidak diperlukan:

```python
app = FastAPI(
    docs_url=None if os.environ.get("ENVIRONMENT") == "production" else "/docs",
    redoc_url=None if os.environ.get("ENVIRONMENT") == "production" else "/redoc",
)
```

## Deploy FastAPI untuk ML Model Serving

FastAPI sangat populer untuk serving machine learning models. Contoh dengan scikit-learn:

```python
# requirements.txt tambahan
scikit-learn>=1.4.0
numpy>=1.26.0
joblib>=1.3.0
```

```python
from fastapi import FastAPI
import joblib
import numpy as np
import os

app = FastAPI()

# Load model saat startup
model = None

@app.on_event("startup")
async def load_model():
    global model
    model = joblib.load("model.pkl")

@app.post("/predict")
async def predict(features: list[float]):
    prediction = model.predict([features])
    return {"prediction": prediction.tolist()}
```

Untuk model yang besar, simpan model di **Secret Files** atau mount via persistent volume.

## Troubleshooting Umum

**"ModuleNotFoundError: No module named 'main'"**
Pastikan file entry point bernama `main.py` dan ada di root repository. Atau override di `helipack.json` dengan path yang benar: `"command": "uvicorn app.main:app ..."`.

**"Connection refused" ke PostgreSQL**
Pastikan `DB_HOST` menggunakan nama service PostgreSQL di canvas Helipod.

**"asyncpg: cannot create a connection"**
Periksa format `DATABASE_URL`: untuk asyncpg harus menggunakan `postgresql+asyncpg://`, bukan `postgresql://`.

**Swagger UI tidak bisa diakses**
Default FastAPI serve docs di `/docs`. Jika tidak muncul, cek apakah `docs_url` di-set ke `None` di kode kamu.

## Kesimpulan

Deploy FastAPI ke Helipod sangat mudah, Helipack mendeteksi framework secara otomatis dan mengurus semua setup server. Kamu tinggal fokus ke business logic API-mu.

Butuh deploy Starlette atau Flask? Baca [Deploy Flask ke Helipod](/blog/cara-deploy-flask-ke-helipod). Ingin tahu detail cara Helipack bekerja? Baca [Helipack: Dockerfile Otomatis](/blog/helipack-dockerfile-otomatis).

Punya pertanyaan? Hubungi kami di [support@helipod.io](mailto:support@helipod.io) atau bergabung ke komunitas di [hangar.helipod.io](https://hangar.helipod.io).
