Skip to content

Commit 0f34a0a

Browse files
Phase 12: Polish API with pagination, sorting, and optional auth
1 parent 0643b57 commit 0f34a0a

1 file changed

Lines changed: 36 additions & 2 deletions

File tree

pythoncms/modules/api/view.py

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
from flask import Blueprint
23
from flask import jsonify
34
from flask import request
@@ -10,13 +11,41 @@
1011
url_prefix="/api/v1",
1112
)
1213

14+
def check_auth():
15+
token = request.headers.get("Authorization")
16+
expected_token = os.environ.get("API_TOKEN")
17+
if expected_token and token != f"Bearer {expected_token}":
18+
return False
19+
return True
20+
1321
@api_blueprint.route("/<string:type_name>", methods=["GET"])
1422
def get_content(type_name):
23+
# Optional Auth
24+
if os.environ.get("API_TOKEN") and not check_auth():
25+
return jsonify({"error": "Unauthorized"}), 401
26+
1527
content_type = ContentType.query.filter_by(name=type_name).first()
1628
if not content_type:
1729
return jsonify({"error": "Content type not found"}), 404
1830

19-
items = ContentItem.query.filter_by(content_type_id=content_type.id).all()
31+
# Pagination & Sorting
32+
limit = request.args.get("limit", default=20, type=int)
33+
offset = request.args.get("offset", default=0, type=int)
34+
sort_by = request.args.get("sort_by", default="created_at", type=str)
35+
order = request.args.get("order", default="desc", type=str)
36+
37+
query = ContentItem.query.filter_by(content_type_id=content_type.id)
38+
39+
# Sorting
40+
if hasattr(ContentItem, sort_by):
41+
column = getattr(ContentItem, sort_by)
42+
if order == "desc":
43+
query = query.order_by(column.desc())
44+
else:
45+
query = query.order_by(column.asc())
46+
47+
total_count = query.count()
48+
items = query.limit(limit).offset(offset).all()
2049

2150
data = []
2251
for item in items:
@@ -29,7 +58,12 @@ def get_content(type_name):
2958
data.append(item_data)
3059

3160
return jsonify({
32-
"count": len(data),
61+
"meta": {
62+
"count": len(data),
63+
"total": total_count,
64+
"limit": limit,
65+
"offset": offset
66+
},
3367
"data": data
3468
})
3569

0 commit comments

Comments
 (0)