0
0
Rest APIprogramming~5 mins

Sorting with sort parameter in Rest API

Choose your learning style9 modes available
Introduction

Sorting with a sort parameter helps you get data in the order you want, like from smallest to largest or newest to oldest.

When you want to show a list of products sorted by price from low to high.
When you need to display recent blog posts first by sorting by date.
When you want to organize search results alphabetically by name.
When you want to sort user comments by popularity or newest.
When you want to sort data in an API response to make it easier to read.
Syntax
Rest API
GET /items?sort=field_name
GET /items?sort=-field_name

The sort parameter is added to the URL query string.

Use a minus sign (-) before the field name to sort in descending order.

Examples
Sort products by price in ascending order (lowest to highest).
Rest API
GET /products?sort=price
Sort posts by date in descending order (newest first).
Rest API
GET /posts?sort=-date
Sort users alphabetically by name.
Rest API
GET /users?sort=name
Sample Program

This program calls an API to get items sorted by rating from highest to lowest. It prints each item's name and rating.

Rest API
import requests

# Example API endpoint
url = 'https://api.example.com/items'

# Sort items by 'rating' descending
params = {'sort': '-rating'}

response = requests.get(url, params=params)

if response.status_code == 200:
    items = response.json()
    for item in items:
        print(f"{item['name']}: {item['rating']}")
else:
    print('Failed to get items')
OutputSuccess
Important Notes

Not all APIs support sorting with a sort parameter; check the API documentation.

Sorting fields must be valid fields in the data, or the API may return an error or ignore the parameter.

Descending order is usually indicated by a minus sign before the field name.

Summary

Use the sort parameter in API requests to control the order of returned data.

Prefix the field with - to sort in descending order.

Sorting makes data easier to understand and use in your app or website.