Building a Simple REST API with FastAPI...
Smita Vatgal
Engineer Golang/Python | Microservices | DevOps | AWS | Kubernetes | CICD | Automation
What is an API?
An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. It consist of Endpoints : URL path, Request, Response, Authentication ( optional ).
Then, what is a REST API?
REST API (Representational State Transfer Application Programming Interface) is a type of web API. It has HTTP methods like GET ( Read all items ), POST ( Create an item ), PUT ( Update an item ), DELETE ( Delete an item ).
There are many ways to build REST APIs, but here we will use a Python framework called FastAPI.
Why choose FASTAPI?
Because it's fast, easy to use, modern and comes with built-in documentation.
Let's dive in...
First, we need to install FastAPI on our machine. Run the following command:
pip install fastapi uvicorn
Next, we will define the Item class. It will have name (string), age (int), and education (string) as its parameters. Since we are building a simple API, we won’t store data in a database but in a simple array/list (in-memory).
领英推荐
from pydantic import BaseModel
class Item(BaseModel):
name: str
age: int
education: str = None
Let's build crud operations...
# POST request
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
items_db.append(item)
return item
The complete code looks like the below. Save it as main.py.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Item(BaseModel):
name: str
age: int
education: str = None
items_db = []
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
items_db.append(item)
return item
@app.get("/items/", response_model=List[Item])
async def get_items():
return items_db
@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
if item_id < 0 or item_id >= len(items_db):
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: Item):
if item_id < 0 or item_id >= len(items_db):
raise HTTPException(status_code=404, detail="Item not found")
items_db[item_id] = item
return item
@app.delete("/items/{item_id}", response_model=Item)
async def delete_item(item_id: int):
if item_id < 0 or item_id >= len(items_db):
raise HTTPException(status_code=404, detail="Item not found")
deleted_item = items_db.pop(item_id)
return deleted_item
Now, run this project using below command.
uvicorn main:app --reload
This will start a development server at https://127.0.0.1:8000. Append the CRUD URLs to use the API. Also, https://127.0.0.1:8000/docs generates documentation and a Swagger UI, where you can see example requests and try out the API.
Further you can extend this API by adding more complex logic based on your project requirements. Whether it's integrating a database, adding authentication and authorization, implementing advanced error handling, or optimizing performance with caching and rate-limiting.. the possibilities are endless!
Happy coding!
Software Engineer | Native Android | Cross-Platform Solutions | API development
1 个月Great start to an essential guide!