This guide will walk through the process of developing a FASTAPI and deploying to an AWS EC2 instance with a custom domain and SSL/HTTPS certification.
Create Virtual Environment
mkdir fastapi
cd fastapi
python3 -m venv env
source env/bin/activate
Create a FASTAPI project
pip install fastapi uvicorn
Create main.py
from fastapi import FastAPIapp =FastAPI()@app.get("/")asyncdefroot():return{"message":"Hello World"}
Launch API
# Launch Uvicorn and load main.py appsudo/home/ubuntu/fastapi/env/bin/uvicornsudo/home/ubuntu/fastapi/main:app--reload
# Create a new service file:sudonano/etc/systemd/system/fastapi.service# Add the following to the new file:[Unit]Description=FastAPIAfter=multi-user.target[Service]Type=simpleRestart=alwaysrestartSec=5sExecStart=/home/ubuntu/folder-name/env/bin/uvicorn /home/ubuntu/folder-name/main:app --reload --port 8000 --host 0.0.0.0 >StandardOutput=append:/home/ubuntu/logs/fastapi.log
StandardError=append:/home/ubuntu/logs/fastapi.log[Install]WantedBy=multi-user.target# Close Nano^Xy[Enter]# Refresh servicessudosystemctldaemon-reload# Enable service (auto-launch e.g. persist when instance is restarted)sudosystemctlenablefastapi.service# Start servicesudosystemctlstartfastapi.service
[Optional] Create a Monitor with Monit
# Create a new Monit file:sudonano/etc/monit/conf.d/fastapi.conf# Add the following to the new file:checkprocessfastapi.servicematching"fastapi.service"startprogram="/bin/systemctl start fastapi.service"stopprogram="/bin/systemctl stop fastapi.service"ifnotexiststhenalertsetlog/var/log/fastapi.log# Reloadsudomonitreload# Restart Monitsudoservicemonitrestart
Websockets
from fastapi import FastAPI, WebSocketimport random# Create applicationapp =FastAPI(title='WebSocket Example')@app.websocket("/ws")asyncdefwebsocket_endpoint(websocket: WebSocket):print('Accepting client connection...')await websocket.accept()whileTrue:try:# Wait for any message from the clientawait websocket.receive_text()# Send message to the client resp ={'value': random.uniform(0, 1)}await websocket.send_json(resp)exceptExceptionas e:print('error:', e)breakprint('Bye..')