-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
154 lines (134 loc) · 4.26 KB
/
Copy pathmain.py
File metadata and controls
154 lines (134 loc) · 4.26 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""
FastAPI Simple Application
A basic but feature-rich FastAPI application demonstrating common patterns.
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional
import uvicorn
import os
# Create FastAPI instance
app = FastAPI(
title="Simple FastAPI Application",
description="A basic FastAPI app with common endpoints and features",
version="1.0.0"
)
# Pydantic models for request/response
class Item(BaseModel):
id: int
name: str
price: float
is_available: bool = True
description: Optional[str] = None
class ItemUpdate(BaseModel):
name: Optional[str] = None
price: Optional[float] = None
is_available: Optional[bool] = None
description: Optional[str] = None
# In-memory storage (for demonstration)
items_db = {
1: {"id": 1, "name": "Laptop", "price": 999.99, "is_available": True, "description": "Gaming laptop"},
2: {"id": 2, "name": "Mouse", "price": 29.99, "is_available": True, "description": "Wireless mouse"},
3: {"id": 3, "name": "Keyboard", "price": 79.99, "is_available": False, "description": "Mechanical keyboard"}
}
# Root endpoint
@app.get("/")
async def root():
"""
Welcome endpoint
"""
return {"message": "Welcome to Simple FastAPI Application!", "version": "1.0.0"}
# Health check endpoint
@app.get("/health")
async def health_check():
"""
Health check endpoint
"""
return {"status": "healthy", "service": "fastapi-simple-app"}
# Get all items
@app.get("/items")
async def get_items(
skip: int = Query(0, ge=0, description="Number of items to skip"),
limit: int = Query(10, ge=1, le=100, description="Number of items to return")
):
"""
Get all items with pagination
"""
items_list = list(items_db.values())
return {
"items": items_list[skip:skip + limit],
"total": len(items_list),
"skip": skip,
"limit": limit
}
# Get item by ID
@app.get("/items/{item_id}")
async def get_item(item_id: int):
"""
Get a specific item by ID
"""
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
# Create new item
@app.post("/items")
async def create_item(item: Item):
"""
Create a new item
"""
if item.id in items_db:
raise HTTPException(status_code=400, detail="Item already exists")
items_db[item.id] = item.dict()
return {"message": "Item created successfully", "item": items_db[item.id]}
# Update item
@app.put("/items/{item_id}")
async def update_item(item_id: int, item_update: ItemUpdate):
"""
Update an existing item
"""
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
# Update only provided fields
for field, value in item_update.dict(exclude_unset=True).items():
items_db[item_id][field] = value
return {"message": "Item updated successfully", "item": items_db[item_id]}
# Delete item
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
"""
Delete an item
"""
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
deleted_item = items_db.pop(item_id)
return {"message": "Item deleted successfully", "deleted_item": deleted_item}
# Search items
@app.get("/search")
async def search_items(q: str = Query(..., description="Search query")):
"""
Search items by name or description
"""
results = []
for item in items_db.values():
if (q.lower() in item["name"].lower() or
(item["description"] and q.lower() in item["description"].lower())):
results.append(item)
return {"query": q, "results": results, "count": len(results)}
# Get available items only
@app.get("/items/available")
async def get_available_items():
"""
Get only available items
"""
available_items = [item for item in items_db.values() if item["is_available"]]
return {"available_items": available_items, "count": len(available_items)}
# Run the application (for development)
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="127.0.0.1",
port=8000,
reload=True,
log_level="info"
)