File size: 1,379 Bytes
d39137f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b8dcf0
d39137f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

app = FastAPI(
    title="FastAPI CRUD Example",
    description="A simple CRUD API with FastAPI",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

items = []

class Item(BaseModel):
    id: int
    name: str
    description: str = None

@app.get("/")
async def root():
    return {"message": "Welcome to FastAPI CRUD API! Visit /docs for Swagger UI."}

@app.get("/items", response_model=List[Item])
async def get_items():
    return items

@app.post("/items", response_model=Item)
async def add_item(item: Item):
    if any(i.id == item.id for i in items):
        raise HTTPException(status_code=400, detail="Item ID already exists")
    items.append(item)
    return item

@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, updated_item: Item):
    for index, item in enumerate(items):
        if item.id == item_id:
            items[index] = updated_item
            return updated_item
    raise HTTPException(status_code=404, detail="Item not found")

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    for item in items:
        if item.id == item_id:
            items.remove(item)
            return {"message": "Item deleted"}
    raise HTTPException(status_code=404, detail="Item not found")