Skip to content
AI appPython

FastAPI + Python AI App

FastAPI service with a /ask endpoint that calls the OpenAI Responses API; secrets loaded from .env.

Open in builder →

7 steps

Shell

Shown with defaults: npm, pip, Node LTS, Python 3.12 and the template's default add-ons.

  1. 1. Check Python 3.12

    runtime

    Make sure Python 3 is installed. Python 3.12 is recommended for this stack.

    bash
    python3 --version
    Expected result
    Prints Python 3.x.
    Verify
    python3 -c "import sys; assert sys.version_info >= (3, 9); print(sys.version)"
    OS notes
    Install from python.org, `brew install python@3.12` (macOS), `sudo apt install python3 python3-venv` (Debian/Ubuntu), or `pyenv install 3.12`. On Windows the `py` launcher comes with the python.org installer.
  2. 2. Create the project folder

    template

    Create an empty folder for the project and move into it. All following commands run inside it.

    bash
    mkdir nvx-ai-apicd nvx-ai-api
    Expected result
    You are inside ./nvx-ai-api
    Verify
    pwd
  3. 3. Create and activate a virtual environment

    template

    A virtual environment (.venv) keeps this project's Python packages isolated from the system Python.

    bash
    python3 -m venv .venvsource .venv/bin/activate
    Expected result
    Your prompt shows (.venv) and `python` points inside .venv.
    Verify
    python -c "import sys; print(sys.prefix)"
    OS notes
    Debian/Ubuntu may need: sudo apt install python3-venv. On Windows, if activation is blocked run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
  4. 4. Install FastAPI, OpenAI SDK and dotenv

    template

    fastapi[standard] includes uvicorn and the `fastapi` CLI. Quotes stop the shell from expanding the brackets.

    bash
    python -m pip install "fastapi[standard]" openai python-dotenv
    Expected result
    Packages installed into .venv.
    Verify
    python -c "import fastapi, openai; print(fastapi.__version__)"
  5. 5. Pin dependencies in requirements.txt

    template

    Freeze the exact installed versions so teammates, CI and Docker install the same packages.

    bash
    python -m pip freeze > requirements.txt
    Expected result
    requirements.txt lists pinned packages (name==version).
    Verify
    cat requirements.txt
  6. 6. Write the API and env template

    template

    main.py exposes /health and /ask. .env.example documents required variables — never commit the real .env.

    bash
    cp .env.example .env
    Files written by this step: main.py, .env.example, .gitignore
    main.py
    import os
    
    from dotenv import load_dotenv
    from fastapi import FastAPI, HTTPException
    from openai import APIError, OpenAI
    from pydantic import BaseModel
    
    load_dotenv()
    
    app = FastAPI(title="nvx-ai-api")
    
    
    class Ask(BaseModel):
        prompt: str
    
    
    @app.get("/health")
    def health():
        return {"ok": True, "service": "nvx-ai-api"}
    
    
    @app.post("/ask")
    def ask(body: Ask):
        if not os.getenv("OPENAI_API_KEY"):
            raise HTTPException(status_code=503, detail="Set OPENAI_API_KEY in .env")
        client = OpenAI()
        try:
            response = client.responses.create(
                model=os.getenv("OPENAI_MODEL", "gpt-6.1-sol"),
                input=body.prompt,
            )
        except APIError as exc:
            raise HTTPException(status_code=502, detail=f"OpenAI error: {exc.__class__.__name__}") from exc
        return {"answer": response.output_text}
    
    .env.example
    OPENAI_API_KEY=
    OPENAI_MODEL=gpt-6.1-sol
    
    .gitignore
    .venv/
    __pycache__/
    .env
    
    Expected result
    main.py and .env exist. Put your key in .env.
    Verify
    python -m py_compile main.py
  7. 7. Run the dev server

    templaterun manually · dev server

    `fastapi dev` runs uvicorn with auto-reload. Interactive docs live at /docs.

    bash
    fastapi dev main.py
    Expected result
    http://127.0.0.1:8000/docs shows Swagger UI.
    Verify
    curl http://127.0.0.1:8000/health