# Sorting results

When you fetch a collection of resources, you can request a specific sort for the results, using the `sort` query parameter.

{% hint style="warning" %}
The value of the `sort` parameter must be a comma-separated list of fields. Pay attention to avoid whitespaces before or after each comma.
{% endhint %}

{% hint style="info" %}
The sort order for each field is ascending unless prefixed with a `-` (minus) in which case it's descending.
{% endhint %}

### Sortable fields

Not all resource attributes can be used as sorting parameters. You can get the full list of the sortable attributes from the [documentation](https://app.gitbook.com/o/-Lfu_B3DKew-kvoEWzTk/s/RWJeylueWkzLadK710XZ/) of each resource in the "List all" section (e.g. [sortable fields for SKUs](https://app.gitbook.com/s/RWJeylueWkzLadK710XZ/skus/list#sortable-fields)).

{% hint style="info" %}
Please note that if you try to sort a collection of resources by a non-sortable attribute the API which will respond with a `400 Bad Request` status code, due to invalid sort criteria.
{% endhint %}

### Examples

#### Sorting the parent resource by one of its attribute

{% tabs %}
{% tab title="Request" %}
The following request fetches a collection of SKUs sorted alphabetically by their code:

```shell
curl -g -X GET \
  'https://yourdomain.commercelayer.io/api/skus?sort=code' \
  -H 'Accept: application/vnd.api+json' \
  -H 'Authorization: Bearer your-access-token'
```

{% endtab %}

{% tab title="Response" %}
On success, the API responds with a `200 OK` status code, returning a paginated collection of the resource objects, sorted in the requested order:

```json
{
  "data": [
    {
      "id": "yzXKjYzaCx",
      "type": "skus",
      "links": {...},
      "attributes": {
        "code": "BABYONBU000000E63E7412MX",
        "name": "Baby's Black Onesie Short Sleeve with Pink Logo (12 Months)",
        "description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        "image_url": "https://img.yourdomain.com/skus/yzXKjYzaCx.png",
        "pieces_per_pack": 6,
        "weight": 300.0,
        "unit_of_weight": "gr",
        "hs_tariff_number": null,
        "do_not_ship": false,
        "do_not_track": false,
        "created_at": "2018-01-01T12:00:00.000Z",
        "updated_at": "2018-01-01T12:00:00.000Z",
        "reference": "ANYREFEFERNCE",
        "metadata": {
          "foo": "bar"
        }
      },
      "relationships": {
        "shipping_category": {
          "links": {...}
        },
        "prices": {
          "links": {...}
        },
        "stock_items": {
          "links": {...}
        },
        "stock_reservations": {
          "links": {...}
        },
        "delivery_lead_times": {
          "links": {...}
        },
        "sku_options": {
          "links": {...}
        },
        { ... }
      },
      "meta": {
        "mode": "test",
        "organization_id": "JxYabZKcAw"
      }
    },
    {
      "other": "... 9 skus (first page)"
    }
  ],
  "meta": {
    "record_count": 140,
    "page_count": 14
  },
  "links": {
    "first": "https://yourdomain.commercelayer.io/api/skus?sort=code&page[number]=1&page[size]=10",
    "next": "https://yourdomain.commercelayer.io/api/skus?sort=code&page[number]=2&page[size]=10",
    "last": "https://yourdomain.commercelayer.io/api/skus?sort=code&page[number]=14&page[size]=10"
  }
}
```

{% content-ref url="pagination" %}
[pagination](https://docs.commercelayer.io/core/pagination)
{% endcontent-ref %}
{% endtab %}
{% endtabs %}

#### Sorting the parent resource by one attribute belonging to a related resource

{% tabs %}
{% tab title="Request" %}
The following request fetches a collection of SKUs sorted alphabetically by the name of the associated shipping category:

```shell
curl -g -X GET \
  'https://yourdomain.commercelayer.io/api/skus?sort=shipping_category.name' \
  -H 'Accept: application/vnd.api+json' \
  -H 'Authorization: Bearer your-access-token'
```

{% endtab %}

{% tab title="Response" %}
On success, the API responds with a `200 OK` status code, returning a paginated collection of the resource objects, sorted in the requested order:

```json
{
  "data": [
    {
      "id": "WFrbSXqyoZ",
      "type": "skus",
      "links": {...},
      "attributes": {
        "code": "TSHIRTMM000000FFFFFFXLXX",
        "name": "Men's Black T-shirt with White Logo (XL)",
        "description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        "image_url": "https://img.yourdomain.com/skus/WFrbSXqyoZ.png",
        "pieces_per_pack": 3,
        "weight": 350.0,
        "unit_of_weight": "gr",
        "hs_tariff_number": null,
        "do_not_ship": false,
        "do_not_track": false,
        "created_at": "2018-01-01T12:00:00.000Z",
        "updated_at": "2018-01-01T12:00:00.000Z",
        "reference": "ANYREFEFERNCE",
        "metadata": {
          "foo": "bar"
        }
      },
      "relationships": {
        "shipping_category": {
          "links": {...}
        },
        "prices": {
          "links": {...}
        },
        "stock_items": {
          "links": {...}
        },
        "stock_reservations": {
          "links": {...}
        },
        "delivery_lead_times": {
          "links": {...}
        },
        "sku_options": {
          "links": {...}
        },
        { ... }
      },
      "meta": {
        "mode": "test",
        "organization_id": "JxYabZKcAw"
      }
    },
    {
      "other": "... 9 skus (first page)"
    }
  ],
  "meta": {
    "record_count": 140,
    "page_count": 14
  },
  "links": {
    "first": "https://yourdomain.commercelayer.io/api/skus?sort=code&page[number]=1&page[size]=10",
    "next": "https://yourdomain.commercelayer.io/api/skus?sort=code&page[number]=2&page[size]=10",
    "last": "https://yourdomain.commercelayer.io/api/skus?sort=code&page[number]=14&page[size]=10"
  }
}
```

{% content-ref url="pagination" %}
[pagination](https://docs.commercelayer.io/core/pagination)
{% endcontent-ref %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
The relationship must be one of the sortable relationships for the parent resource (in the example above the shipping category is one of the SKU's [sortable](https://app.gitbook.com/s/RWJeylueWkzLadK710XZ/skus/list#sortable-fields) relationships), the attribute must be one of the filterable ones for the related resource (in the example above the name is one of the shipping category's [sortable](https://app.gitbook.com/s/RWJeylueWkzLadK710XZ/shipping_categories/list#sortable-fields) attributes).
{% endhint %}

#### Sorting related resources

{% tabs %}
{% tab title="Request" %}
The following request fetches the list of orders associated with a certain customer, sorted by their creation date (descending):

```shell
curl -g -X GET \
  'https://yourdomain.commercelayer.io/api/customers/xYZkjABcde/orders?sort=-created_at' \
  -H 'Accept: application/vnd.api+json' \
  -H 'Authorization: Bearer your-access-token'
```

{% endtab %}

{% tab title="Response" %}
On success, the API responds with a `200 OK` status code, returning a paginated collection of the related resource objects, sorted in the requested order:

```json
{
  "data": [
    {
      "id": "kjVLxYzbAc",
      "type": "orders",
      "links": {...},
      "attributes": {
        "number": 1234,
        "autorefresh": true,
        "status": "pending",
        "payment_status": "unpaid",
        "fulfillment_status": "unfulfilled",
        "guest": false,
        "editable": true,
        "customer_email": "john@example.com",
        "language_code": "en",
        "currency_code": "USD",
        "tax_included": false,
        "tax_rate": null,
        "freight_taxable": null,
        "requires_billing_info": false,
        "country_code": "US",
        "shipping_country_code_lock": null,
        "coupon_code": null,
        "gift_card_code": null,
        "gift_card_or_coupon_code": null,
        "subtotal_amount_cents": 3480,
        "subtotal_amount_float": 34.8,
        "formatted_subtotal_amount": "$34.80",
        "shipping_amount_cents": 700,
        "shipping_amount_float": 7.0,
        "formatted_shipping_amount": "$7.00",
        "payment_method_amount_cents": 0,
        "payment_method_amount_float": 0.0,
        "formatted_payment_method_amount": "$0.00",
        "discount_amount_cents": 0,
        "discount_amount_float": 0.0,
        "formatted_discount_amount": "$0.00",
        "adjustment_amount_cents": 0,
        "adjustment_amount_float": 0.0,
        "formatted_adjustment_amount": "$0.00",
        "gift_card_amount_cents": 0,
        "gift_card_amount_float": 0.0,
        "formatted_gift_card_amount": "$0.00",
        "total_tax_amount_cents": 0,
        "total_tax_amount_float": 0.0,
        "formatted_total_tax_amount": "$0.00",
        "subtotal_tax_amount_cents": 0,
        "subtotal_tax_amount_float": 0.0,
        "formatted_subtotal_tax_amount": "$0.00",
        "shipping_tax_amount_cents": 0,
        "shipping_tax_amount_float": 0.0,
        "formatted_shipping_tax_amount": "$0.00",
        "payment_method_tax_amount_cents": 0,
        "payment_method_tax_amount_float": 0.0,
        "formatted_payment_method_tax_amount": "$0.00",
        "adjustment_tax_amount_cents": 0,
        "adjustment_tax_amount_float": 0.0,
        "formatted_adjustment_tax_amount": "$0.00",
        "total_amount_cents": 4180,
        "total_amount_float": 41.8,
        "formatted_total_amount": "$41.80",
        "total_taxable_amount_cents": 4180,
        "total_taxable_amount_float": 41.8,
        "formatted_total_taxable_amount": "$41.80",
        "subtotal_taxable_amount_cents": 3480,
        "subtotal_taxable_amount_float": 34.8,
        "formatted_subtotal_taxable_amount": "$34.80",
        "shipping_taxable_amount_cents": 700,
        "shipping_taxable_amount_float": 7.0,
        "formatted_shipping_taxable_amount": "$7.00",
        "payment_method_taxable_amount_cents": 0,
        "payment_method_taxable_amount_float": 0.0,
        "formatted_payment_method_taxable_amount": "$0.00",
        "adjustment_taxable_amount_cents": 0,
        "adjustment_taxable_amount_float": 0.0,
        "formatted_adjustment_taxable_amount": "$0.00",
        "total_amount_with_taxes_cents": 4180,
        "total_amount_with_taxes_float": 41.8,
        "formatted_total_amount_with_taxes": "$41.80",
        "fees_amount_cents": 0,
        "fees_amount_float": 0.0,
        "formatted_fees_amount": "$0.00",
        "duty_amount_cents": null,
        "duty_amount_float": null,
        "formatted_duty_amount": null,
        "skus_count": 1,
        "line_item_options_count": 0,
        "shipments_count": 1,
        "payment_source_details": null,
        "token": "y0ur-t0K3n",
        "cart_url": null,
        "return_url": null,
        "terms_url": null,
        "privacy_url": null,
        "checkout_url": "https://your-checkout-url/kjVLxYzbAc",
        "placed_at": null,
        "approved_at": null,
        "cancelled_at": null,
        "payment_updated_at": null,
        "fulfillment_updated_at": null,
        "refreshed_at": null,
        "archived_at": null,
        "expires_at": null,
        "created_at": "2018-01-01T12:00:00.000Z",
        "updated_at": "2018-01-01T12:00:00.000Z",
        "reference": "",
        "reference_origin": null,
        "metadata": {}
      },
      "relationships": {
        "market": {
          "links": {...}
        },
        "customer": {
          "links": {...}
        },
        "shipping_address": {
          "links": {...}
        },
        "billing_address": {
          "links": {...}
        },
        "available_payment_methods": {
          "links": {...}
        },
        "available_customer_payment_sources": {
          "links": {...}
        },
        "payment_method": {
          "links": {...}
        },
        "payment_source": {
          "links": {...}
        },
        "line_items": {
          "links": {...}
        },
        "shipments": {
          "links": {...}
        },
        "transactions": {
          "links": {...}
        },
        "authorizations": {
          "links": {...}
        },
        "captures": {
            "links": {...}
        },
        "voids": {
          "links": {...}
        },
        "refunds": {
          "links": {...}
        },
        "order_subscriptions": {
            "links": {...}
        },
        "order_copies": {
          "links": {...}
        },
        "attachments": {
          "links": {...}
        }
      },
      "meta": {
        "mode": "test",
        "organization_id": "JxYabZKcAw"
      }
    },
    {
      "other": "... 9 orders (first page)"
    }
  ],
  "meta": {
      "record_count": 70,
      "page_count": 7
  },
  "links": {
    "first": "https://yourdomain.commercelayer.io/api/customers/xYZkjABcde/orders?sort=-created_at&page[number]=1&page[size]=10",
    "next": "https://yourdomain.commercelayer.io/api/customers/xYZkjABcde/orders?sort=-created_at&page[number]=2&page[size]=10",
    "last": "https://yourdomain.commercelayer.io/api/customers/xYZkjABcde/orders?sort=-created_at&page[number]=7&page[size]=10"
  }
}
```

{% content-ref url="pagination" %}
[pagination](https://docs.commercelayer.io/core/pagination)
{% endcontent-ref %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
You can get the full list of sortable attributes from the [documentation](https://app.gitbook.com/o/-Lfu_B3DKew-kvoEWzTk/s/RWJeylueWkzLadK710XZ/) of each resource.
{% endhint %}
