kedro_datasets.api.APIDataset

class kedro_datasets.api.APIDataset(url, method='GET', load_args=None, save_args=None, credentials=None, metadata=None)[source]

APIDataset loads/saves data from/to HTTP(S) APIs. It uses the python requests library: https://requests.readthedocs.io/en/latest/

Example usage for the YAML API:

usda:
  type: api.APIDataset
  url: https://quickstats.nass.usda.gov
  params:
    key: SOME_TOKEN,
    format: JSON,
    commodity_desc: CORN,
    statisticcat_des: YIELD,
    agg_level_desc: STATE,
    year: 2000

Example usage for the Python API:

 from kedro_datasets.api import APIDataset


 dataset = APIDataset(
...     url="https://quickstats.nass.usda.gov",
...     load_args={
...         "params": {
...             "key": "SOME_TOKEN",
...             "format": "JSON",
...             "commodity_desc": "CORN",
...             "statisticcat_des": "YIELD",
...             "agg_level_desc": "STATE",
...             "year": 2000
...         }
...     },
...     credentials=("username", "password")
... )
 data = dataset.load()

APIDataset can also be used to save output on a remote server using HTTP(S) methods.

 example_table = '{"col1":["val1", "val2"], "col2":["val3", "val4"]}'

 dataset = APIDataset(
...     method = "POST",
...     url = "url_of_remote_server",
...     save_args = {"chunk_size":1}
... )
 dataset.save(example_table)

On initialisation, we can specify all the necessary parameters in the save args dictionary. The default HTTP(S) method is POST but PUT is also supported. Two important parameters to keep in mind are timeout and chunk_size. timeout defines how long our program waits for a response after a request. chunk_size, is only used if the input of save method is a list. It will divide the request into chunks of size chunk_size. For example, here we will send two requests each containing one row of our example DataFrame. If the data passed to the save method is not a list, APIDataset will check if it can be loaded as JSON. If true, it will send the data unchanged in a single request. Otherwise, the _save method will try to dump the data in JSON format and execute the request.

Attributes

DEFAULT_SAVE_ARGS

Methods

exists()

Checks whether a data set's output already exists by calling the provided _exists() method.

from_config(name, config[, load_version, ...])

Create a data set instance using the configuration provided.

load()

Loads data by delegation to the provided load method.

release()

Release any cached data.

save(data)

Saves data by delegation to the provided save method.

DEFAULT_SAVE_ARGS = {'auth': None, 'chunk_size': 100, 'headers': None, 'json': None, 'params': None, 'timeout': 60}
__init__(url, method='GET', load_args=None, save_args=None, credentials=None, metadata=None)[source]

Creates a new instance of APIDataset to fetch data from an API endpoint.

Parameters:
  • url (str) – The API URL endpoint.

  • method (str) – The method of the request. GET, POST, PUT are the only supported methods

  • load_args (Optional[Dict[str, Any]]) – Additional parameters to be fed to requests.request. https://requests.readthedocs.io/en/latest/api/#requests.request

  • save_args (Optional[Dict[str, Any]]) – Options for saving data on server. Includes all parameters used during load method. Adds an optional parameter, chunk_size which determines the size of the package sent at each request.

  • credentials (Union[Tuple[str, str], List[str], AuthBase, None]) – Allows specifying secrets in credentials.yml. Expected format is ('login', 'password') if given as a tuple or list. An AuthBase instance can be provided for more complex cases.

  • metadata (Optional[Dict[str, Any]]) – Any arbitrary metadata. This is ignored by Kedro, but may be consumed by users or external plugins.

Raises:

ValueError – if both auth and credentials are specified or used unsupported RESTful API method.

exists()

Checks whether a data set’s output already exists by calling the provided _exists() method.

Return type:

bool

Returns:

Flag indicating whether the output already exists.

Raises:

DatasetError – when underlying exists method raises error.

classmethod from_config(name, config, load_version=None, save_version=None)

Create a data set instance using the configuration provided.

Parameters:
  • name – Data set name.

  • config – Data set config dictionary.

  • load_version – Version string to be used for load operation if the data set is versioned. Has no effect on the data set if versioning was not enabled.

  • save_version – Version string to be used for save operation if the data set is versioned. Has no effect on the data set if versioning was not enabled.

Returns:

An instance of an AbstractDataset subclass.

Raises:

DatasetError – When the function fails to create the data set from its config.

load()

Loads data by delegation to the provided load method.

Return type:

TypeVar(_DO)

Returns:

Data returned by the provided load method.

Raises:

DatasetError – When underlying load method raises error.

release()

Release any cached data.

Raises:

DatasetError – when underlying release method raises error.

Return type:

None

save(data)

Saves data by delegation to the provided save method.

Parameters:

data (TypeVar(_DI)) – the value to be saved by provided save method.

Raises:
  • DatasetError – when underlying save method raises error.

  • FileNotFoundError – when save method got file instead of dir, on Windows.

  • NotADirectoryError – when save method got file instead of dir, on Unix.

Return type:

None