Add sort_order parameter to GET endpoints for date sorting

This commit is contained in:
Automated Action 2025-05-19 09:59:35 +00:00
parent 7f4634d292
commit 2e7ff1df5a
2 changed files with 46 additions and 0 deletions

View File

@ -78,6 +78,7 @@ This is a FastAPI application for generating and managing invoices. It allows yo
- `limit`: Maximum number of records to return (default: 100)
- `fields`: Comma-separated list of fields to include in the response (e.g., "id,invoice_number,total_amount")
- `status`: Filter invoices by status (e.g., "PENDING", "PAID", "CANCELLED")
- `sort_order`: Sort by creation date, either "asc" (oldest first) or "desc" (newest first, default)
- `GET /api/v1/invoices/{invoice_id}`: Get a specific invoice by ID
- Query parameters:
- `fields`: Comma-separated list of fields to include in the response (e.g., "id,invoice_number,total_amount")
@ -194,6 +195,29 @@ To combine with other parameters:
GET /api/v1/invoices?status=PENDING&fields=id,invoice_number,total_amount&limit=5
```
### Sorting
The API supports sorting invoices by their creation date.
#### How to Use Sorting:
1. Add a `sort_order` query parameter to the GET request
2. Specify one of the allowed values:
- `asc`: Ascending order (oldest invoices first)
- `desc`: Descending order (newest invoices first, this is the default)
#### Example:
To get invoices in chronological order (oldest first):
```
GET /api/v1/invoices?sort_order=asc
```
To combine sorting with other parameters:
```
GET /api/v1/invoices?sort_order=desc&status=PENDING&limit=10
```
### Available Fields:
Invoices have the following fields that can be filtered:

View File

@ -75,6 +75,7 @@ def get_invoices(
limit: int = 100,
fields: Optional[str] = None,
status: Optional[str] = None,
sort_order: Optional[str] = "desc",
db: Session = Depends(get_db)
):
"""
@ -87,6 +88,8 @@ def get_invoices(
If not provided, all fields will be returned.
- status: Filter invoices by status (e.g., "PENDING", "PAID", "CANCELLED")
If not provided, all invoices regardless of status will be returned.
- sort_order: Sort invoices by date_created field, either "asc" for ascending or "desc" for descending order.
Default is "desc" (newest first).
"""
# Build the query with filters
query = db.query(Invoice)
@ -104,6 +107,25 @@ def get_invoices(
# Apply the filter
query = query.filter(Invoice.status == status)
# Apply sorting
if sort_order:
# Validate sort_order value
allowed_sort_orders = ["asc", "desc"]
if sort_order.lower() not in allowed_sort_orders:
raise HTTPException(
status_code=400,
detail=f"Sort order must be one of {', '.join(allowed_sort_orders)}"
)
# Apply sorting based on sort_order
if sort_order.lower() == "asc":
query = query.order_by(Invoice.date_created.asc())
else: # Default to 'desc'
query = query.order_by(Invoice.date_created.desc())
else:
# Default sorting (descending - newest first)
query = query.order_by(Invoice.date_created.desc())
# Apply pagination
invoices = query.offset(skip).limit(limit).all()