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://api.spaceflightnewsapi.net/v4/articles",
...     load_args={
...         "params": {
...             "news_site": "NASA",
...             "launch": "65896761-b6ca-4df3-9699-e077a360c52a",  # Artemis I
...         }
...     },
... )
 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="https://dummyjson.com/products/add",
...     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 dataset's output already exists by calling the provided _exists() method.

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

Create a dataset 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.

to_config()

Converts the dataset instance into a dictionary-based configuration for serialization.

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.html#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()[source]

Checks whether a dataset’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)[source]

Create a dataset instance using the configuration provided.

Parameters:
  • name (str) – Data set name.

  • config (dict[str, Any]) – Data set config dictionary.

  • load_version (Optional[str]) – Version string to be used for load operation if the dataset is versioned. Has no effect on the dataset if versioning was not enabled.

  • save_version (Optional[str]) – Version string to be used for save operation if the dataset is versioned. Has no effect on the dataset if versioning was not enabled.

Return type:

AbstractDataset

Returns:

An instance of an AbstractDataset subclass.

Raises:

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

load()[source]

Loads data by delegation to the provided load method.

Return type:

Response

Returns:

Data returned by the provided load method.

Raises:

DatasetError – When underlying load method raises error.

release()[source]

Release any cached data.

Raises:

DatasetError – when underlying release method raises error.

Return type:

None

save(data)[source]

Saves data by delegation to the provided save method.

Parameters:

data (Any) – 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:

Response

to_config()[source]

Converts the dataset instance into a dictionary-based configuration for serialization. Ensures that any subclass-specific details are handled, with additional logic for versioning and caching implemented for CachedDataset.

Adds a key for the dataset’s type using its module and class name and includes the initialization arguments.

For CachedDataset it extracts the underlying dataset’s configuration, handles the versioned flag and removes unnecessary metadata. It also ensures the embedded dataset’s configuration is appropriately flattened or transformed.

If the dataset has a version key, it sets the versioned flag in the configuration.

Removes the metadata key from the configuration if present.

Return type:

dict[str, Any]

Returns:

A dictionary containing the dataset’s type and initialization arguments.