Responses
A Civis API call from client.<endpoint>.<method> returns one of the “response” objects:
civis.PaginatedResponseif<method>is a “list” call withiterator=True,civis.ListResponseif<method>is a “list” call that either doesn’t have aniteratorargument or hasiterator=False, or
>>> 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.
- class civis.PaginatedResponse(path: str, initial_params: dict[str, Any], endpoint)[source]
A generator of
civis.Responseobjects, 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'])
- class civis.ListResponse(responses: list[T_Response], headers: dict | None = None)[source]
A list of
civis.Responseobjects.- 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.
Helper Functions
- civis.find(object_list: Iterable[Response], filter_func: Callable | None = None, **kwargs) list[Response][source]
Filter
civis.Responseobjects.- 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.Responseobjects.- 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))isTrue.- **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 objectobjfrom the input iterable to be included in the returned list, all the keys must be attributes ofobj, plus any one of the following conditions for a given key:valueis a one-argument function andbool(value(getattr(obj, key)))is equal toTruevalueis eitherTrueorFalse, andgetattr(obj, key) is valueisTruegetattr(obj, key) == valueisTrue
- Returns:
- list
See also
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.Responseobject.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,Noneis returned.- Returns:
- object or None
See also