Server-Side Scripting/REST API/Python (FastAPI)

routers/lesson13.py

edit
# This program creates and displays a temperature database with options to
# insert, update, and delete records using a REST API.
#
# Test using cURL commands.
#
# Insert countries:
# curl -X POST -d "country=Bulgaria&temperature=45.2%20°C" http://localhost:5000/lesson13/countries
# curl -X POST -d "country=Canada&temperature=45%20°C" http://localhost:5000/lesson13/countries
# curl -X POST -d "country=Finland&temperature=37.2%20°C" http://localhost:5000/lesson13/countries
# curl -X POST -d "country=Germany&temperature=42.6%20°C" http://localhost:5000/lesson13/countries
# curl -X POST -d "country=Japan&temperature=41%20°C" http://localhost:5000/lesson13/countries
# curl -X POST -d "country=United%20States%20of%20America&temperature=56.7%20°C" http://localhost:5000/lesson13/countries
#
# Get countries:
# curl -X GET http://localhost:5000/lesson13/countries
#
# Get country #6:
# curl -X GET http://localhost:5000/lesson13/countries/6
#
# Update country #6:
# curl -X PUT -d "country=United%20States%20of%20America&temperature=55%20°C" http://localhost:5000/lesson13/countries/6
#
# Get country #6:
# curl -X GET http://localhost:5000/lesson13/countries/6
#
# Delete country #6:
# curl -X DELETE http://localhost:5000/lesson13/countries/6
#
# Get Countries:
# curl -X GET http://localhost:5000/lesson13/countries
#
# References:
#   https://en.wikibooks.org/wiki/Python_Programming
#   https://fastapi.tiangolo.com/tutorial/
#   https://www.baeldung.com/curl-rest

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

class Country(BaseModel):
    id: int = None
    country: str
    temperature: str

countries = []
lastID = 0
instructions = '''
<p>Use cURL commands to test the REST API.</p>
<p>Insert countries:<br>
curl -X POST -d "country=Bulgaria&temperature=45.2%20°C" http://host/example/countries<br>
curl -X POST -d "country=Canada&temperature=45%20°C" http://host/example/countries<br>
curl -X POST -d "country=Finland&temperature=37.2%20°C" http://host/example/countries<br>
curl -X POST -d "country=Germany&temperature=42.6%20°C" http://host/example/countries<br>
curl -X POST -d "country=Japan&temperature=41%20°C" http://host/example/countries<br>
curl -X POST -d "country=United%20States%20of%20America&temperature=56.7%20°C" http://host/example/countries</p>
<p>Get countries:<br>
curl -X GET http://host/example/countries</p>
<p>Get country #6:<br>
curl -X GET http://host/example/countries/6</p>
<p>Update country #6:<br>
curl -X PUT -d "country=United%20States%20of%20America&temperature=55%20°C" http://host/example/countries/6</p>
<p>Get country #6.<br>
curl -X GET http://host/example/countries/6</p>
<p>Delete country #6:<br>
curl -X DELETE http://host/example/countries/6</p>
<p>Get Countries:<br>
curl -X GET http://host/example/countries</p>
'''

router = APIRouter(prefix="/lesson13")
templates = Jinja2Templates(directory="templates")

@router.get("/", response_class=HTMLResponse)
async def get_lesson13(request: Request):
    result = instructions.replace("http://host/example/", str(request.url))
    return result

@router.get("/countries")
async def get_countries():
    return countries

@router.get("/countries/{id}")
async def get_country(id: int):
    for country in countries:
        if country["id"] == id:
            return country

    raise HTTPException(status_code=404, detail="ID not found")

@router.post("/countries")
async def post_country(request: Request):
    form = dict(await request.form())
    global lastID
    lastID += 1

    country = {
        "id": lastID,
        "country": form.get("country"),
        "temperature": form.get("temperature")
    }

    countries.append(country)
    return country

@router.put("/countries/{id}")
async def put_country(request: Request, id: int):
    form = dict(await request.form())
    for country in countries:
        if country["id"] == id:
            country["country"] = form.get("country"),
            country["temperature"] = form.get("temperature")
            return country
    
    raise HTTPException(status_code=404, detail="ID not found")

@router.delete("/countries/{id}")
async def delete_country(id: int):
    for index in range(len(countries)):
        if countries[index]["id"] == id:
            country = countries.pop(index)
            return country
    
    raise HTTPException(status_code=404, detail="ID not found")

Try It

edit

See Server-Side Scripting/Routes and Templates/Python (FastAPI) to create a test environment.

See Also

edit