Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
55 lines (44 loc) · 1.71 KB
/
Copy pathmain.py
File metadata and controls
55 lines (44 loc) · 1.71 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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
# 1. Создаем приложение
app = FastAPI(title="Мой первый API")
# 2. Модели данных (Pydantic)
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
# Временная "база данных" (в реальности тут была бы БД из Урока 12)
fake_db = {}
# 3. GET запрос (главная страница)
@app.get("/")
def read_root():
return {"message": "Добро пожаловать в API!"}
# 4. GET с параметром пути
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id not in fake_db:
raise HTTPException(status_code=404, detail="Item not found")
return fake_db[item_id]
# 5. POST запрос (создание)
@app.post("/items/{item_id}")
def create_item(item_id: int, item: Item):
if item_id in fake_db:
raise HTTPException(status_code=400, detail="Item already exists")
# Сохраняем в "базу"
fake_db[item_id] = item
return {"message": "Item created", "item": item}
# 6. PUT запрос (обновление)
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
if item_id not in fake_db:
raise HTTPException(status_code=404, detail="Item not found")
fake_db[item_id] = item
return {"message": "Item updated", "item": item}
# 7. DELETE запрос
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id not in fake_db:
raise HTTPException(status_code=404, detail="Item not found")
del fake_db[item_id]
return {"message": "Item deleted"}