SamRR_75
SamRR_75

Reputation: 809

How to add a sort/order parameter to an API url query string?

I am using a sample API URL (reqres.in/api/users?page=2) that returns the following data in Postman:

{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
    {
        "id": 7,
        "email": "[email protected]",
        "first_name": "Michael",
        "last_name": "Lawson",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
    },
    {
        "id": 8,
        "email": "[email protected]",
        "first_name": "Lindsay",
        "last_name": "Ferguson",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"
    },
    {
        "id": 9,
        "email": "[email protected]",
        "first_name": "Tobias",
        "last_name": "Funke",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg"
    },
    {
        "id": 10,
        "email": "[email protected]",
        "first_name": "Byron",
        "last_name": "Fields",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg"
    },
    {
        "id": 11,
        "email": "[email protected]",
        "first_name": "George",
        "last_name": "Edwards",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg"
    },
    {
        "id": 12,
        "email": "[email protected]",
        "first_name": "Rachel",
        "last_name": "Howell",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg"
    }
]}

I want to add a query string parameter that will allow me to sort the data by the first_namekey/value pair so that Byron Fields will be the first result and Tobias Funke will be the last result.

I have tried using query parameters such as &sort=+first_name, &sort=sort=first_name.asc, and &sortBy=+first_namebut none of these query strings appear to be doing the trick.

Is there an API query parameter that will allow me to sort the data by the first_name key/value pair?

Any help would be greatly appreciated.

Upvotes: 1

Views: 6306

Answers (2)

wetooa
wetooa

Reputation: 1

I may be wrong but I did this const data = await Data.find({}).sort(<key>) in my project using mongoose.

Upvotes: 0

Danny Dainton
Danny Dainton

Reputation: 25921

It's a public API that doesn't appear to have that URL filter option, couldn't find the documentation though. An API doesn't automagically have those types of features, you would need to implement them first. :)

You could achieve this in Postman by using the Lodash sortBy function but it's doing it all after the response has been received:

If you add this to the Tests tab, you will see the output in the Console:

console.log(_.sortBy(pm.response.json().data, 'first_name'));

Postman

Upvotes: 1

Related Questions