How To: Use Query Strings to interact with API Results

Django REST Framework (DRF) interacts directly with the ORM to provide powerful fine tuning of queries that are run against the database when collecting data for API responses. This is a non-exhaustive guide on how to use these out-of-the-box query string parameters to filter, sort, search, limit or extend the data returned by a given API endpoint.

Customer-facing docs about this can be found here: https://docs.cloudbolt.io/articles/#!cloudbolt-latest-docs/api-conventions

fields param

Limit the amount of data you get back to only fields you care about.

Example:

  • Only get name field from orders:

    • /orders?fields=name

Notes:

Sometimes this can also marginally improve response time from the server.

attributes param

If a given model attribute is not by default included in the API response, it is often possible to add it using the attributes query param. It’s also possible to add model fields of related models, using the syntax {parent_model_attribute}.{related_model_attribute}

Examples:

  • Add the primary key (aka auto-incrementing “id”) of a model to the response (by default, APIv3 returns the global id):

    • ?attributes=pk

  • Add resource type icon to blueprints data:

    • /blueprints?attributes=resource_type.icon

Notes:

  • In some endpoints, the serializer might have customized the item dictionary in such a way that it limits the amount of customization that can be achieved with the attributes param.

  • If the attribute you’re trying to add is a field on a related model, and there is no relation on a given instance of the model, the attribute will not be included as a key in the instances data.

ordering param

Sort results ascending or descending on a given model field.

Example:

  • Name: ?ordering=name

    • Descending: ?ordering=-name

filter and exclude params

These are the most powerful parameters for tuning the result set to your needs. They allow you to craft filtering queries using any of Django’s queryset field lookups (see quick reference below). The query string format follows the pattern: ?filter={field}__{lookup}:{value}. It’s also possible to filter on related model attributes, with format ?filter={parentField}__{relatedField}__{lookup}:{value}.

The filter query param also accepts a list of dicts, which it will chain together to create an OR’d query.

Examples:

  • Filter /blueprints by multiple groups using global id

    • ?filter=groups__global_id__in:[{gid}, {gid}]

  • Filter /blueprints by multiple categories using category name (related model is called Tag):

    • ?filter=tags__name__in:[{cat}, ...]

  • Search blueprint name and description for the word “database”, case insensitive:

    • ?filter=[{"name__icontains":"database"},{"description__icontains":"database"}]

Notes:

  • The available field lookup functions also include a number of reasonably fast SQL text search helpers that can be leveraged to easily implement case sensitive or insensitive searching with text fragments:

    • Blueprint title, case insensitive starts with: ?filter=name__istartswith:{text frag}

    • Blueprint description, case insensitive contains: ?filter=name__icontains:{text frag}

Field lookup reference

Keyword

Description

contains

Contains the phrase

icontains

Same as contains, but case-insensitive

date

Matches a date

day

Matches a date (day of month, 1-31) (for dates)

endswith

Ends with

iendswith

Same as endswidth, but case-insensitive

exact

An exact match

iexact

Same as exact, but case-insensitive

in

Matches one of the values

isnull

Matches NULL values

gt

Greater than

gte

Greater than, or equal to

hour

Matches an hour (for datetimes)

lt

Less than

lte

Less than, or equal to

minute

Matches a minute (for datetimes)

month

Matches a month (for dates)

quarter

Matches a quarter of the year (1-4) (for dates)

range

Match between

regex

Matches a regular expression

iregex

Same as regex, but case-insensitive

second

Matches a second (for datetimes)

startswith

Starts with

istartswith

Same as startswith, but case-insensitive

time

Matches a time (for datetimes)

week

Matches a week number (1-53) (for dates)

week_day

Matches a day of week (1-7) 1 is sunday

iso_week_day

Matches a ISO 8601 day of week (1-7) 1 is monday

year

Matches a year (for dates)

iso_year

Matches an ISO 8601 year (for dates)

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.