"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

February 10, 2023

EC2 - AWS Flask Deployment Example

Deploying Sample API code 

#All credits to https://youtu.be/34cqrIp5ANg, Customized and simplified it for my reference
import json
from fastapi import FastAPI, HTTPException
import os
app = FastAPI()
BOOKS_FILE = "books.json"
BOOK_DATABASE = ['The great gatsby','atomic habits','norwegien wood']
if os.path.exists(BOOKS_FILE):
with open(BOOKS_FILE,'r') as f:
BOOKS_DATABASE = json.load(f)
#GET method to written list of books
@app.get('/list-books')
async def list_books():
return {'books':BOOK_DATABASE}
@app.get('/book-by-index/{index}')
async def book_by_index(index: int):
if (index < 0 or index >= len(BOOK_DATABASE)):
raise HTTPException(404,f'index {index} is more than 4 books')
else:
return {'book':BOOK_DATABASE[index]}
#This missed backslash was a miss and was debugging sometime
@app.post('/add-book')
async def add_book(book: str):
BOOK_DATABASE.append(book)
return {'message':f' {book[0]} is added'}


Creating an EC2 Free t2 instance

Basic Ubuntu


Allow Access


Save Public IP

Launch Instance


Run Updated Packages and the below commands

#Borrowed / Custmized detailed steps from https://github.com/pixegami/fastapi-tutorial
Step 1 - Update packages
sudo apt-get update
Step 2 - Install pip
sudo apt install -y python-pip nginx
sudo apt install python3-pip
Step 3 - Config file creation
sudo vim /etc/nginx/sites-enabled/fastapi_nginx
Step 4 - Contents
server {
listen 80;
server_name 34.221.96.208;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
Step 5 - Restart Service
sudo service nginx restart
Step 6 - Download file
wget https://gist.githubusercontent.com/siva2k16/400922b893865051c99fd24d6f3e7b2f/raw/6e5320641ae6e49ebf94a1666dc2914953114012/fastapiexample.py
Step 7 - Install packages
pip3 install fastapi
pip3 install uvicorn
Step 8 - Run Example code
python3 -m uvicorn fastapiexample:app
Step 9 - Allow inbound communication
One more key step - Enable inbound on port 80 in security groups
Step 10 - Examples to run
http://127.0.0.1:8000/docs#
http://34.221.96.208:80/docs#
view raw commands hosted with ❤ by GitHub


Ref - Simplified code example Link

Allow Access to Port 80. HTTP




Run from browser and access APIs

Keep Exploring!!!

No comments: