Responses

A Civis API call from client.<endpoint>.<method> returns one of the “response” objects:

>>> import civis
>>> client = civis.APIClient()
>>> response = client.scripts.get(12345)
>>> response
Response({'id': 12345,
          'name': 'some script name',
          'created_at': '2018-06-11T20:43:07.000Z',
          'updated_at': '2018-06-11T20:43:19.000Z',
          'author': Response({'id': 67890,
                              'name': 'Platform User Name',
                              'username': 'platformusername',
                              'initials': 'PUN',
                              'online': False}),
          ...

To retrieve information from a civis.Response object, use the attribute syntax:

>>> response.id
12345
>>> response.name
'some script name'
>>> response.author
Response({'id': 67890,
          'name': 'Platform User Name',
          'username': 'platformusername',
          'initials': 'PUN',
          'online': False})
>>> response.author.username
'platformusername'

civis.APIClient is type-annotated for the returned civis.Response object of a given Civis API endpoint’s method, including the expected attributes. These type annotations facilitate code development and testing:

  • If your IDE has auto-complete support, typing response. from the example above prompts possible attributes {id, name, author, ...}.

  • Type checking (by tools such as mypy) in test suites and continuous integration helps to catch issues such as typos and unexpected attributes.

Alternatively, the “getitem” syntax can also be used:

>>> response['id']
12345
>>> response['author']
Response({'id': 67890,
          'name': 'Platform User Name',
          'username': 'platformusername',
          'initials': 'PUN',
          'online': False})

Although the “getitem” syntax would lose the benefits of the attribute syntax listed above, the “getitem” syntax is more user-friendly when an attribute name is available programmatically, e.g., response[foo] versus getattr(response, foo).

Note that civis.Response objects are read-only. If you need to modify information from a response object, call civis.Response.json() to get a dictionary representation of the response object. You can then modify this dictionary as needed:

>>> response.arguments = ...  # !!! Raises CivisImmutableResponseError
>>> response['arguments'] = ...  # !!! Raises CivisImmutableResponseError
>>>
>>> response_json = response.json()
>>> response_json['arguments'] = {'new_arg_for_a_similar_script': 'some_value'}
>>> # use response_json downstream, e.g., to create a new Civis Platform script

Response Types

class civis.Response(json_data: dict[str, Any] | None, *, headers: dict | None = None, snake_case: bool = True, from_json_values: bool = False)[source]

Custom Civis response object.

Attributes:
json_datadict | None

This is json_data as it is originally returned to the user without the key names being changed. None is used if the original response returned a 204 No Content response.

headersdict

This is the header for the API call without changing the key names.

calls_remainingint

Number of API calls remaining before rate limit is reached.

rate_limitint

Total number of calls per API rate limit period.

Methods

get(key[, default])

Get the value for the given key.

items()

Return an iterator of the key-value pairs in the response.

json([snake_case])

Return the JSON data.

get(key, default=None)[source]

Get the value for the given key.

items()[source]

Return an iterator of the key-value pairs in the response.

json(snake_case: bool = True) dict[str, Any][source]

Return the JSON data.

Parameters:
snake_casebool, optional

If True (the default), return the keys in snake case. If False, return the keys in camel case.

Returns:
dict
class civis.PaginatedResponse(path: str, initial_params: dict[str, Any], endpoint)[source]

A generator of civis.Response objects, for paginated API calls.

Parameters:
pathstr

Make GET requests to this path.

initial_paramsdict

Query params that should be passed along with each request. Note that if initial_params contains the key page_num, it will be ignored. The given dict is not modified.

endpointcivis.base.Endpoint

An endpoint used to make API requests.

Methods

json([snake_case])

Return the JSON data of all responses.

Notes

This response is returned automatically by endpoints which support pagination when the iterator kwarg is specified.

Examples

>>> import civis
>>> client = civis.APIClient()
>>> queries = client.queries.list(iterator=True)
>>> for query in queries:
...    print(query['id'])
json(snake_case: bool = True) list[dict[str, Any]][source]

Return the JSON data of all responses.

Parameters:
snake_casebool, optional

If True (the default), return the keys in snake case. If False, return the keys in camel case.

Returns:
list[dict]
class civis.ListResponse(responses: list[T_Response], headers: dict | None = None)[source]

A list of civis.Response objects.

Parameters:
responseslist[civis.Response]

A list of response objects to be stored in this list.

headersdict, optional

Headers to be attached to the list response. The headers info is available as an attribute, so that it can be accessed even when the list is empty.

Methods

json([snake_case])

Return the JSON data of all responses in the list.

json(snake_case: bool = True) list[dict[str, Any]][source]

Return the JSON data of all responses in the list.

Parameters:
snake_casebool, optional

If True (the default), return the keys in snake case. If False, return the keys in camel case.

Returns:
list[dict]

Helper Functions

civis.find(object_list: Iterable[Response], filter_func: Callable | None = None, **kwargs) list[Response][source]

Filter civis.Response objects.

Parameters:
object_listiterable

An iterable of arbitrary objects, particularly those with attributes that can be targeted by the filters in kwargs. A major use case is an iterable of civis.Response objects.

filter_funccallable, optional

A one-argument function. If specified, kwargs are ignored. An object from the input iterable is kept in the returned list if and only if bool(filter_func(object)) is True.

**kwargs

Key-value pairs for more fine-grained filtering; they cannot be used in conjunction with filter_func. All keys must be strings. For an object obj from the input iterable to be included in the returned list, all the keys must be attributes of obj, plus any one of the following conditions for a given key:

  • value is a one-argument function and bool(value(getattr(obj, key))) is equal to True

  • value is either True or False, and getattr(obj, key) is value is True

  • getattr(obj, key) == value is True

Returns:
list

See also

civis.find_one

Examples

>>> import civis
>>> client = civis.APIClient()
>>> # creds is a list of civis.Response objects
>>> creds = client.credentials.list()
>>> # target_creds contains civis.Response objects
>>> # with the attribute 'name' == 'username'
>>> target_creds = find(creds, name='username')
civis.find_one(object_list: Iterable[Response], filter_func: Callable | None = None, **kwargs) Response | None[source]

Return one satisfying civis.Response object.

The arguments are the same as those for civis.find(). If more than one object satisfies the filtering criteria, the first one is returned. If no satisfying objects are found, None is returned.

Returns:
object or None

See also

civis.find