Sorting helps organize data so it's easier to find or understand. Using ascending (asc) or descending (desc) order tells the system how to arrange the data.
0
0
Sort direction (asc, desc) in Rest API
Introduction
When you want to list products from cheapest to most expensive.
When showing recent messages starting from the newest.
When displaying names in alphabetical order.
When sorting scores from highest to lowest in a game leaderboard.
Syntax
Rest API
GET /items?sort=field_name&direction=asc GET /items?sort=field_name&direction=desc
sort specifies which field to sort by.
direction can be asc for ascending or desc for descending order.
Examples
This request sorts users by their age from youngest to oldest.
Rest API
GET /users?sort=age&direction=asc
This request sorts products by price from highest to lowest.
Rest API
GET /products?sort=price&direction=desc
This request sorts books alphabetically by their title.
Rest API
GET /books?sort=title&direction=asc
Sample Program
This program shows how to request sorted data from an API by specifying the sort field and direction. It prints the full URL used for each request.
Rest API
import requests # Example API endpoint url = 'https://api.example.com/items' # Sort items by 'name' in ascending order params_asc = {'sort': 'name', 'direction': 'asc'} response_asc = requests.get(url, params=params_asc) # Sort items by 'name' in descending order params_desc = {'sort': 'name', 'direction': 'desc'} response_desc = requests.get(url, params=params_desc) print('Ascending order request URL:', response_asc.url) print('Descending order request URL:', response_desc.url)
OutputSuccess
Important Notes
Not all APIs support sorting; check the API documentation first.
If you omit the direction, some APIs default to ascending order.
Sorting large data sets may slow down the response time.
Summary
Sort direction controls how data is ordered: ascending (asc) or descending (desc).
Use query parameters like sort and direction in API requests to specify sorting.
Sorting makes data easier to read and find.