-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
88 lines (66 loc) · 2.01 KB
/
Copy pathmain.py
File metadata and controls
88 lines (66 loc) · 2.01 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
Learn FastAPI
Simple FastAPI tutorial with CRUD operations
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI(title="Learn FastAPI", version="1.0.0")
# Data model
class Item(BaseModel):
id: Optional[int] = None
name: str
description: Optional[str] = None
price: float
# In-memory database
items_db = []
next_id = 1
@app.get("/")
def read_root():
"""Root endpoint"""
return {"message": "Welcome to FastAPI Tutorial!"}
@app.get("/items", response_model=List[Item])
def get_items():
"""Get all items"""
return items_db
@app.get("/items/{item_id}", response_model=Item)
def get_item(item_id: int):
"""Get item by ID"""
for item in items_db:
if item.id == item_id:
return item
raise HTTPException(status_code=404, detail="Item not found")
@app.post("/items", response_model=Item)
def create_item(item: Item):
"""Create new item"""
global next_id
item.id = next_id
next_id += 1
items_db.append(item)
return item
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, updated_item: Item):
"""Update item"""
for i, item in enumerate(items_db):
if item.id == item_id:
updated_item.id = item_id
items_db[i] = updated_item
return updated_item
raise HTTPException(status_code=404, detail="Item not found")
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
"""Delete item"""
for i, item in enumerate(items_db):
if item.id == item_id:
items_db.pop(i)
return {"message": "Item deleted"}
raise HTTPException(status_code=404, detail="Item not found")
if __name__ == "__main__":
import uvicorn
print("\n" + "="*60)
print(" FASTAPI TUTORIAL")
print("="*60)
print("\nStarting server...")
print("API docs: http://127.0.0.1:8000/docs")
print("="*60 + "\n")
uvicorn.run(app, host="127.0.0.1", port=8000)