-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_api.py
More file actions
112 lines (87 loc) · 3.06 KB
/
basic_api.py
File metadata and controls
112 lines (87 loc) · 3.06 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
"""
Basic API Example
This is a simple REST API built with WebSpark that demonstrates:
- Basic routing
- GET and POST methods
- JSON responses
- Simple data storage (in-memory)
"""
from webspark.core import View, WebSpark, path
from webspark.http import Context
from webspark.utils import HTTPException
# In-memory storage for our examples
items = [
{"id": 1, "name": "Item 1", "description": "First item"},
{"id": 2, "name": "Item 2", "description": "Second item"},
]
next_id = 3
class ItemsView(View):
"""Handle operations on the collection of items."""
def handle_get(self, ctx: Context):
"""Return all items."""
ctx.json({"items": items})
def handle_post(self, ctx: Context):
"""Create a new item."""
global next_id
data = ctx.body
# Simple validation
if not data or "name" not in data:
raise HTTPException("Name is required", status=400)
# Create new item
new_item = {
"id": next_id,
"name": data["name"],
"description": data.get("description", ""),
}
items.append(new_item)
next_id += 1
ctx.json(new_item, status=201)
class ItemDetailView(View):
"""Handle operations on a single item."""
def handle_get(self, ctx: Context):
"""Return a specific item by ID."""
item_id = int(ctx.path_params["id"])
item = next((item for item in items if item["id"] == item_id), None)
if not item:
raise HTTPException("Item not found", status=404)
ctx.json(item)
def handle_put(self, ctx: Context):
"""Update a specific item."""
item_id = int(ctx.path_params["id"])
data = ctx.body
# Find the item
item_index = next(
(i for i, item in enumerate(items) if item["id"] == item_id), None
)
if item_index is None:
raise HTTPException("Item not found", status=404)
# Update the item
items[item_index]["name"] = data.get("name", items[item_index]["name"])
items[item_index]["description"] = data.get(
"description", items[item_index]["description"]
)
ctx.json(items[item_index])
def handle_delete(self, ctx: Context):
"""Delete a specific item."""
global items
item_id = int(ctx.path_params["id"])
# Find and remove the item
item = next((item for item in items if item["id"] == item_id), None)
if not item:
raise HTTPException("Item not found", status=404)
items = [item for item in items if item["id"] != item_id]
ctx.json({"message": "Item deleted"}, status=204)
# Create the app
app = WebSpark(debug=True)
# Add routes
app.add_paths(
[
path("/items", view=ItemsView.as_view()),
path("/items/:id", view=ItemDetailView.as_view()),
]
)
if __name__ == "__main__":
# For development purposes, you can run this with a WSGI server like:
# gunicorn examples.basic_api:app
print("Basic API Example")
print("Run with: gunicorn examples.basic_api:app")