April 17, 2024 by CodeFlowerHorn
Creating a Synchronous API with FastAPI and Swagger in Python
The ability to create a synchronous API is essential for any Python developer. We'll take you step-by-step through the process of creating a reliable synchronous API with FastAPI, and Swagger, a crucial tool for API documentation.
Prerequisite
Ubuntu requirements
Open a terminal and enter this command(s)
sudo apt install uvicorn -y
python3 -m pip install fastapi[all]
Windows requirements
Open a terminal and enter this command(s)
python3 -m pip install uvicorn
python3 -m pip install fastapi[all]
Import libraries
import uvicorn
from fastapi import FastAPI, status
from fastapi.middleware.cors import CORSMiddleware
Defined your variables
app = FastAPI() # fastapi object
id_counter = [0] # temporary id
books = {} # store our temporary data
app = FastAPI(
title="Books API",
description="A simple api for CRUD operations",
version="1.0",
swagger_ui_parameters={
"defaultModelsExpandDepth": -1
}
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
Defined your http endpoints
@app.get("/book/{id}", status_code=status.HTTP_200_OK, tags=["Book"])
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, tags=["Book"])
def get_books():
data = {
"message": "Get",
"results": books
}
return data
@app.post("/book", status_code=status.HTTP_201_CREATED, tags=["Book"])
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, tags=["Book"])
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, tags=["Book"])
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(
title="Books API",
description="A simple api for CRUD operations",
version="1.0",
swagger_ui_parameters={
"defaultModelsExpandDepth": -1
}
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
app = FastAPI() # fastapi object
id_counter = [0] # temporary id
books = {} # store our temporary data
@app.get("/book/{id}", description="Get book by id")
def get_book(id: int):
if id in books:
return books[id]
else:
return {
"message": "Item not found"
}
@app.get("/books", description="Get all books")
def get_books():
return books
@app.post("/book", description="Create a 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}", description="Update a book")
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}", description="Delete a book")
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