Usecase1 using FastAPI

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Welcome to my API!"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}

To run it:

uvicorn main:app --reload

→ Visit http://127.0.0.1:8000/docs for auto-generated Swagger UI.


🧠 Summary

TermMeaningExample
APIInterface between systemsGoogle Maps API
RESTful APIAPI following REST principles using HTTP/users/1 via GET
Python ModulesFastAPI, Flask, DRF, BottleBuild APIs

Usecase 2


⚙️ Step 1: A Simple RESTful API Example

# file: main.py
from fastapi import FastAPI

app = FastAPI()

# Sample database (in memory)
users = {
    1: {"id": 1, "name": "Rajeev", "age": 30},
    2: {"id": 2, "name": "Priya", "age": 28}
}

# ✅ GET method - Read user
@app.get("/users/{user_id}")
def get_user(user_id: int):
    user = users.get(user_id)
    if user:
        return user
    return {"error": "User not found"}

# ✅ POST method - Create user
@app.post("/users")
def create_user(user: dict):
    new_id = max(users.keys()) + 1
    user["id"] = new_id
    users[new_id] = user
    return {"message": "User created", "user": user}

🧠 Step 2: What Happens Behind the Scenes

🔹 Example 1 — GET /users/1

Request (from client → server):

GET /users/1 HTTP/1.1
Host: localhost:8000

Response (server → client):

{
  "id": 1,
  "name": "Rajeev",
  "age": 30
}

🧩 What This Shows

REST WordMeaning Here
RepresentationalThe representation of the user resource is sent as JSON.
StateThe JSON data shows the current state of user 1 (name, age).
TransferThe state’s representation is transferred over HTTP using the GET method.

🔹 Example 2 — POST /users

Request:

POST /users HTTP/1.1
Content-Type: application/json

{
  "name": "Asha",
  "age": 25
}

Response:

{
  "message": "User created",
  "user": {
    "id": 3,
    "name": "Asha",
    "age": 25
  }
}

🧩 What This Shows

REST WordMeaning Here
RepresentationalThe new user info is represented as JSON.
StateThe server updates the resource’s state (adds new user).
TransferThe representation of the new state is transferred back in response.

🌐 REST Principles Illustrated

Client–Server separation → Client requests, server responds.
Statelessness → Every request is independent.
Uniform Interface → Standard HTTP verbs (GET, POST, etc.)
Representation → Data exchanged as JSON.
Transfer → Done over HTTP.


Usecase3 ✅ — we’ll now build a full RESTful API example that supports all CRUD operations
(Create, Read, Update, Delete) in both FastAPI and Flask,
while clearly showing where Representational, State, and Transfer apply.


🚀 PART 1: FastAPI – Full REST Example

# file: fastapi_rest.py
from fastapi import FastAPI, HTTPException

app = FastAPI()

# In-memory "database"
users = {
    1: {"id": 1, "name": "Rajeev", "age": 30},
    2: {"id": 2, "name": "Priya", "age": 28}
}

# 🟩 CREATE (POST)
@app.post("/users")
def create_user(user: dict):
    new_id = max(users.keys()) + 1 if users else 1
    user["id"] = new_id
    users[new_id] = user
    return {"message": "User created", "user": user}

# 🟦 READ (GET)
@app.get("/users/{user_id}")
def get_user(user_id: int):
    if user_id not in users:
        raise HTTPException(status_code=404, detail="User not found")
    return users[user_id]

# 🟨 UPDATE (PUT - full replace)
@app.put("/users/{user_id}")
def update_user(user_id: int, new_data: dict):
    if user_id not in users:
        raise HTTPException(status_code=404, detail="User not found")
    new_data["id"] = user_id
    users[user_id] = new_data
    return {"message": "User replaced", "user": new_data}

# 🟧 PARTIAL UPDATE (PATCH)
@app.patch("/users/{user_id}")
def patch_user(user_id: int, partial_data: dict):
    if user_id not in users:
        raise HTTPException(status_code=404, detail="User not found")
    users[user_id].update(partial_data)
    return {"message": "User partially updated", "user": users[user_id]}

# 🟥 DELETE
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
    if user_id not in users:
        raise HTTPException(status_code=404, detail="User not found")
    del users[user_id]
    return {"message": f"User {user_id} deleted"}

Run this app:

uvicorn fastapi_rest:app --reload

You can test all endpoints at 👉 http://127.0.0.1:8000/docs (auto-generated Swagger UI 🎯)


⚙️ How REST Concepts Apply

HTTP VerbActionREST Concept
GETRead a resourceTransfer current representation of state
POSTCreate new resourceTransfer new representation, server updates state
PUTReplace resource fullyTransfer full representation, replaces old state
PATCHModify partiallyTransfer partial representation, updates part of state
DELETERemove resourceTransfer command that changes state (resource removed)

🧩 Representational · State · Transfer Summary

TermIn CodeExplanation
RepresentationalJSON bodies sent/receivedEach resource (user) is represented as JSON
StateThe user’s data (name, age)Shows current state of resource
TransferHTTP methods (GET/POST/PUT/DELETE)Moves representations between client & server

🐍 PART 2: Flask – Same REST Example

# file: flask_rest.py
from flask import Flask, jsonify, request

app = Flask(__name__)

users = {
    1: {"id": 1, "name": "Rajeev", "age": 30},
    2: {"id": 2, "name": "Priya", "age": 28}
}

# 🟩 CREATE
@app.route("/users", methods=["POST"])
def create_user():
    user = request.get_json()
    new_id = max(users.keys()) + 1 if users else 1
    user["id"] = new_id
    users[new_id] = user
    return jsonify({"message": "User created", "user": user}), 201

# 🟦 READ
@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
    user = users.get(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404
    return jsonify(user)

# 🟨 UPDATE
@app.route("/users/<int:user_id>", methods=["PUT"])
def update_user(user_id):
    if user_id not in users:
        return jsonify({"error": "User not found"}), 404
    new_data = request.get_json()
    new_data["id"] = user_id
    users[user_id] = new_data
    return jsonify({"message": "User replaced", "user": new_data})

# 🟧 PARTIAL UPDATE
@app.route("/users/<int:user_id>", methods=["PATCH"])
def patch_user(user_id):
    if user_id not in users:
        return jsonify({"error": "User not found"}), 404
    partial_data = request.get_json()
    users[user_id].update(partial_data)
    return jsonify({"message": "User partially updated", "user": users[user_id]})

# 🟥 DELETE
@app.route("/users/<int:user_id>", methods=["DELETE"])
def delete_user(user_id):
    if user_id not in users:
        return jsonify({"error": "User not found"}), 404
    del users[user_id]
    return jsonify({"message": f"User {user_id} deleted"})

Run this app:

python flask_rest.py

Then open 👉 http://127.0.0.1:5000/users/1 to test endpoints via Postman or curl.


⚡ Difference Summary: FastAPI vs Flask

FeatureFastAPIFlask
Type checking✅ Built-in (auto validates request body)❌ Manual validation needed
Auto docs✅ Swagger UI at /docs❌ Requires extra package like Flask-RESTX
Async support✅ Native⚙️ Needs async extension
Speed🚀 Very fast (based on ASGI + Pydantic)🐢 Slower (WSGI)
Ideal forModern APIs, AI/ML appsSimpler/smaller APIs

Pages: 1 2 3

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *