April 17, 2024 by CodeFlowerHorn

Step-by-Step Guide to Building a Synchronous API in Python


For many applications that need a simple, sequential execution procedure, implementing a synchronous Python API is necessary. This tutorial will show you how to use Python to create a reliable synchronous API.

Prerequisite

Ubuntu requirements
                                    sudo apt install uvicorn -y
python3 -m pip install fastapi[all]
                                
Windows requirements
                                    python3 -m pip install uvicorn
python3 -m pip install fastapi[all]
                                
Import libraries
                                    import uvicorn
from fastapi import FastAPI, status
                                
Defined your variables
                                    app = FastAPI() # fastapi object
id_counter = [0] # temporary id
books = {} # store our temporary data
                                
Defined your http endpoints
                                    @app.get("/book/{id}", status_code=status.HTTP_200_OK)
def get_book(id: int):
    data = None
    if id in books:
        data = {
            "message": "Get",
            "results": books[id]
        }
    else:
        data = {
            "message": "Item not found",
            "results": {}
        }

    return data

@app.get("/books", status_code=status.HTTP_200_OK)
def get_books():
    data = {
        "message": "Get",
        "results": books
    }

    return data

@app.post("/book", status_code=status.HTTP_201_CREATED)
def create_book(title: str, author: str, genre: str):
    id_counter[0] = id_counter[0] + 1 
    id = id_counter[0]
    books[id] = {
        "id": id,
        "title": title,
        "author": author,
        "genre": genre
    }

    data = {
        "message": "Created",
        "results": books[id]
    }
    
    return data

@app.put("/book/{id}", status_code=status.HTTP_200_OK)
def update_book(id: int, title: str = None, author: str = None, genre: str = None):
    data = None
    if id in books:
        if title != None:
            books[id]["title"] = title
        if author != None:
            books[id]["author"] = author
        if genre != None:
            books[id]["genre"] = genre
        data = {
            "message": "Updated",
            "results": books[id]
        }
    else:
        data = {
            "message": "Item not found",
            "results": {}
        }

    return data

@app.delete("/book/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_book(id: int):
    data = None
    if id in books: 
        results = books[id]
        del books[id]
        data = {
            "message": "Deleted",
            "results": results
        }
    else:
        data = {
            "message": "Item not found",
            "results": {}
        }

    return data
                                
Program entrypoint
                                    if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
                                
Full code
Create a file and name it main.py and copy & paste the code below
                                    import uvicorn 
from fastapi import FastAPI

app = FastAPI() # fastapi object
id_counter = [0] # temporary id
books = {} # store our temporary data

@app.get("/book/{id}")
def get_book(id: int):
    if id in books:
        return books[id]
    else:
        return {
            "message": "Item not found"
        }

@app.get("/books")
def get_books():
    return books

@app.post("/book")
def create_book(title: str, author: str, genre: str):
    id_counter[0] = id_counter[0] + 1 
    id = id_counter[0]
    books[id] = {
        "title": title,
        "author": author,
        "genre": genre
    }
    return books[id]

@app.put("/book/{id}")
def update_book(id: int, title: str = None, author: str = None, genre: str = None):
    if id in books:
        if title != None:
            books[id]["title"] = title
        if author != None:
            books[id]["author"] = author
        if genre != None:
            books[id]["genre"] = genre
        return {
            "message": "Updated"
        }
    else:
        return {
            "message": "Item not found"
        }

@app.delete("/book/{id}")
def delete_book(id: int):
    if id in books: 
        del books[id]
        return {
            "message": "Deleted"
        }
    else:
        return {
            "message": "Item not found"
        }
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
                                
Run the python script for Ubuntu
                                    uvicorn main:app --host 0.0.0.0 --port 8000 --reload
                                
Run the python script for Windows
                                    python3 -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload