Guides / Python API
Host a Python API with FastAPI
1. Install Python tools
apt update
apt install -y python3-venv
mkdir -p /opt/api
cd /opt/api
python3 -m venv venv
venv/bin/pip install fastapi uvicorn
2. Create your app
Save as /opt/api/main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "Hello from natbox"}
3. Keep it running
Save as /etc/systemd/system/api.service, using your own port:
[Unit]
Description=My FastAPI app
After=network.target
[Service]
WorkingDirectory=/opt/api
ExecStart=/opt/api/venv/bin/uvicorn main:app --host 0.0.0.0 --port 10002
Restart=always
User=www-data
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable --now api
systemctl status api
4. Test it
From your own computer, using your own port:
curl http://natbox.io:10002/
You should see {"message":"Hello from natbox"}. If you use a firewall, allow the port first with ufw allow 10002/tcp.
5. Add your domain and HTTPS
For a public API, link a domain and put a web server in front. Caddy gets HTTPS certificates for you, and nginx works too. Proxy to your app on 127.0.0.1:10002.
A small API fits on Nano. Choose Box if it also runs a database.