### Install SDMX from Source (Standard Install) Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Install the sdmx package from the source directory using setup.py. This performs a standard installation. ```bash python setup.py install ``` -------------------------------- ### Install and Install Pre-commit Hooks Source: https://github.com/khaeru/sdmx/blob/main/doc/dev.md Install pre-commit and set up git hooks to ensure code style compliance on each commit. ```shell pip install pre-commit pre-commit install ``` -------------------------------- ### Install SDMX Package Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Install the sdmx package using pip. This is the standard method for installing Python packages. ```bash pip install sdmx1 ``` -------------------------------- ### Install SDMX from Source (Editable Mode) Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Install the sdmx package in editable mode from the source directory. This is recommended for development as changes to the code are reflected immediately. ```bash pip install --editable . ``` -------------------------------- ### Install SDMX with Optional Dependencies Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Install the sdmx package along with optional dependencies for extra features like caching, documentation building, or testing. Use comma-separated values for multiple extras. ```bash pip install sdmx1[cache] ``` ```bash pip install sdmx1[cache,docs,tests] ``` -------------------------------- ### Install SDMX from Source with Optional Dependencies (Editable) Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Install the sdmx package from source in editable mode, including optional dependencies. This allows for development with extra features enabled. ```bash pip install --editable .[cache] ``` ```bash pip install --editable .[cache,docs,tests] ``` -------------------------------- ### Install SDMX-ML XML Schema Documents Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Installs SDMX-ML XML Schema documents required for XML validation. You can specify a directory for installation and the version of the schema to download. ```python import sdmx from sdmx.util import Version sdmx.install_schemas(version=Version["3.0.0"]) ``` -------------------------------- ### Install Official SDMX Schemas Source: https://github.com/khaeru/sdmx/blob/main/doc/howto/validate.md Installs the official SDMX schema files to a local cache for validation. This only needs to be run once per SDMX-ML version. ```python import sdmx sdmx.install_schemas() ``` ```python import sdmx sdmx.install_schemas(version="3.0") ``` -------------------------------- ### BaseWriter Example Source: https://github.com/khaeru/sdmx/blob/main/doc/api/writer.md Demonstrates how to create a custom writer by subclassing BaseWriter and registering functions for specific model types. ```python >>> MyWriter = BaseWriter('my') ``` ```python >>> @MyWriter.register >>> def _(obj: sdmx.model.ItemScheme): >>> ... code to write an ItemScheme ... >>> return result ``` ```python >>> @MyWriter.register >>> def _(obj: sdmx.model.Codelist): >>> ... code to write a Codelist ... >>> return result ``` -------------------------------- ### sdmx.install_schemas Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Installs SDMX-ML XML Schema documents, which are necessary for validating XML files using `validate_xml()`. ```APIDOC ## sdmx.install_schemas(schema_dir: Path | None = None, version: str | Version = Version.2.1) -> Path ### Description Install SDMX-ML XML Schema documents for use with [`validate_xml()`](#sdmx.validate_xml). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) * **Path** (Path) - The path containing the installed schemas. If schema_dir is given, the return value is identical to the parameter. #### Response Example None ``` -------------------------------- ### Get Dataflows for COMP Source Source: https://github.com/khaeru/sdmx/blob/main/doc/sources.md Instantiate the COMP client and retrieve available dataflows. This is useful for identifying available data within the Directorate General for Competition. ```python COMP = sdmx.Client("COMP") sm = COMP.dataflow() print(sm.dataflow) ``` -------------------------------- ### Run SDMX Tests Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Run the test suite for the sdmx package after installing from source. This command executes the tests using pytest. ```bash pytest ``` -------------------------------- ### Querying Data with Key and Time Period Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Demonstrates constructing a query for SDMX data by specifying dimension values for the 'CURRENCY' dimension and setting a start period to filter older data. ```python from sdmx import Client client = Client() # Example 1: Key as a list of values for a dimension client.get(resource_id='EXR', key=['USD', 'JPY'], params={'startPeriod': '2020-01-01'}) # Example 2: Key as a dictionary mapping dimension to value client.get(resource_id='EXR', key={'CURRENCY': 'USD'}, params={'startPeriod': '2020-01-01'}) # Example 3: Key as a tuple of dimension-value pairs client.get(resource_id='EXR', key=(('CURRENCY', 'USD'), ('FREQ', 'D')), params={'startPeriod': '2020-01-01'}) # Example 4: Key as a string (for a single dimension) client.get(resource_id='EXR', key='USD', params={'startPeriod': '2020-01-01'}) ``` -------------------------------- ### Clone SDMX Repository Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Clone the sdmx repository from Github to install from source. This is useful for development or accessing the latest code. ```bash git clone git@github.com:khaeru/sdmx.git ``` -------------------------------- ### Configure HTTP Connection with Proxy Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Configure the HTTP connection for the SDMX client by passing keyword arguments recognized by requests.request(). This example shows how to specify a proxy server for all outgoing requests. ```python from sdmx import Client client = Client( 'ecb', proxies={'http': 'http://user:pass@host:port'} ) ``` -------------------------------- ### Configure IMF SDMX Client for SDMX 3.0.0 API Source: https://github.com/khaeru/sdmx/blob/main/doc/sources.md This example demonstrates how to configure an SDMX client to use the SDMX 3.0.0 API provided by sdmxcentral.imf.org. It involves modifying the client's source URL and specifying the desired SDMX version. ```python import sdmx from sdmx.format import Version client = sdmx.Client("IMF") client.source.url = "https://sdmxcentral.imf.org/sdmx/v2" client.source.versions = {Version["3.0.0"]} ``` -------------------------------- ### get Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Retrieves an SDMX resource. This method allows fetching specific resources by type and ID, with options for caching and dry runs. ```APIDOC ## get ### Description Retrieves an SDMX resource by its type and ID. Supports caching and dry run options. ### Method `get` ### Parameters * **resource_type** (`str` or `sdmx.Resource` or `None`) - Optional - The type of the resource to retrieve. * **resource_id** (`str` or `None`) - Optional - The ID of the resource to retrieve. * **tofile** (`os.PathLike` or `IO` or `None`) - Optional - File path or IO object to save the resource to. * **use_cache** (`bool`) - Optional - Whether to use the cache for retrieval. Defaults to `False`. * **dry_run** (`bool`) - Optional - If `True`, returns a `requests.Request` object instead of the message. Defaults to `False`. * **version** (`str`) - Optional - The version of the resource to retrieve. Defaults to 'latest'. ### Returns * **`sdmx.message.Message` or `requests.Request`**: The requested SDMX message or a `Request` object if `dry_run` is `True`. ### Raises * **NotImplementedError**: If the source does not support the given `resource_type` and `force` is not `True`. ``` -------------------------------- ### sdmx.model.common.ComponentList Source: https://github.com/khaeru/sdmx/blob/main/doc/api/model.md Represents a list of components, with methods to append, extend, get, and getdefault components. It also includes attributes for annotations, ID, URI, URN, and an auto-order counter. ```APIDOC ## class sdmx.model.common.ComponentList Bases: [`IdentifiableArtefact`](#sdmx.model.common.IdentifiableArtefact), `Generic`[`CT`] #### append(value: CT) → None Append *value* to [`components`](#sdmx.model.common.ComponentList.components). #### auto_order *= 1* Counter used to automatically populate [`DimensionComponent.order`](#sdmx.model.common.DimensionComponent.order) values. #### components *: list[CT]* #### extend(values: Iterable[CT]) → None Extend [`components`](#sdmx.model.common.ComponentList.components) with *values*. #### get(id) → CT Return the component with the given *id*. #### getdefault(id, cls=None, **kwargs) → CT Return or create the component with the given *id*. If the component is automatically created, its `Dimension.order` attribute is set to the value of [`auto_order`](#sdmx.model.common.ComponentList.auto_order), which is then incremented. * **Parameters:** * **id** (`str`) – Component ID. * **cls** (`type`, *optional*) – Hint for the class of a new object. * **kwargs** – Passed to the constructor of [`Component`](#sdmx.model.common.Component), or a Component subclass if [`components`](#sdmx.model.common.ComponentList.components) is overridden in a subclass of ComponentList. #### id *: str* Unique identifier of the object. #### uri *: str | None* Universal resource identifier that may or may not be resolvable. #### urn *: str | None* Universal resource name. For use in SDMX registries; all registered objects have a URN. ``` -------------------------------- ### SDMX Version Patterns Source: https://github.com/khaeru/sdmx/blob/main/doc/api/model.md Defines regular expressions for parsing SDMX version strings for versions 2.1 and 3.0. Version 2.1 examples include '1.0', while 3.0 examples can include extensions like '1.0.0-draft'. ```python import re VERSION_PATTERNS = { '2_1': re.compile('^(?P[0-9]+(?:\\.[0-9]+){1})$'), '3_0': re.compile('^(?P[0-9]+(?:\\.[0-9]+){2})(-(?P.+))?$') } ``` -------------------------------- ### Access SDMX Data via URL Source: https://github.com/khaeru/sdmx/blob/main/doc/howto.md Create an sdmx Client and use the get() method with a URL to access data from any SDMX 2.1 compliant web service. ```python import sdmx c = sdmx.Client() c.get(url='https://sdmx.example.org/path/to/webservice', ...) ``` -------------------------------- ### Request Dataflow with All References Source: https://github.com/khaeru/sdmx/blob/main/doc/howto.md Example of requesting a dataflow and its associated objects (DSD, code lists, etc.) using the 'references' parameter set to 'all'. This is efficient for retrieving a complete set of related SDMX objects in a single request. ```python response = some_agency.dataflow('SOME_ID', params={'references': 'all'}) ``` -------------------------------- ### Structure-Specific Data Format Example Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Shows the more concise structure-specific XML format for SDMX-ML data, which omits explicit identification of dimensions and attributes for smaller message sizes. ```xml ``` -------------------------------- ### Generic Data Format Example Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Illustrates the generic XML format for SDMX-ML data, where values associated with an Observation are explicitly identified as dimensions or attributes. ```xml ``` -------------------------------- ### Querying UNICEF Data with Dataflow and DSD Source: https://github.com/khaeru/sdmx/blob/main/doc/sources.md This example demonstrates how to query data from UNICEF, first by obtaining the data structure definition (DSD) from a specific dataflow, and then using that DSD to query for a particular indicator. ```python import sdmx UNICEF = sdmx.Client("UNICEF") # Use the dataflow ID to obtain the data structure definition ds d = UNICEF.dataflow("CONSOLIDATED", provider="CD2030").structure[0] # Use the DSD to construct a query for indicator D5 (“Births”) client.data("CONSOLIDATED", key=dict(INDICATOR="D5"), dsd=dsd) ``` -------------------------------- ### get(resource_type, resource_id, tofile, use_cache, dry_run, **kwargs) Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Retrieves SDMX data or metadata from the client's source. Resources can be specified by type and ID, or by a resource object. The method supports various options for constraining data, handling files, caching, and dry runs. ```APIDOC ## get(resource_type, resource_id, tofile, use_cache, dry_run, **kwargs) ### Description Retrieve SDMX data or metadata. (Meta)data is retrieved from the [`source`](sources.md#module-sdmx.source) of the current Client. The item(s) to retrieve can be specified in one of two ways: 1. resource_type, resource_id: These give the type (see [`Resource`](#sdmx.Resource)) and, optionally, ID of the item(s). If the resource_id is not given, all items of the given type are retrieved. 2. a resource object, i.e. a [`MaintainableArtefact`](api/model.md#sdmx.model.common.MaintainableArtefact): resource_type and resource_id are determined by the object’s class and [`id`](api/model.md#sdmx.model.common.IdentifiableArtefact.id) attribute, respectively. ### Method GET (implied by retrieval operation) ### Endpoint Not explicitly defined, operates on the client's configured source. ### Parameters #### Path Parameters None #### Query Parameters * **resource_type** (`str` or [`Resource`](#sdmx.Resource), *optional*) – Type of resource to retrieve. * **resource_id** (`str`, *optional*) – ID of the resource to retrieve. * **tofile** (`str` or `PathLike` or file-like object, *optional*) – File path or file-like to write SDMX data as it is received. * **use_cache** (`bool`, *optional*) – If `True`, return a previously retrieved [`Message`](#sdmx.message.Message) from `cache`, or update the cache with a newly-retrieved Message. * **dry_run** (`bool`, *optional*) – If `True`, prepare and return a `requests.Request` object, but do not execute the query. The prepared URL and headers can be examined by inspecting the returned object. * **dsd** ([`DataStructureDefinition`](api/model.md#sdmx.model.common.BaseDataStructureDefinition)) – Existing object used to validate the key argument. If not provided, an additional query executed to retrieve a DSD in order to validate the key. * **force** (`bool`) – If `True`, execute the query even if the [`source`](sources.md#module-sdmx.source) does not support queries for the given resource_type. Default: `False`. * **headers** (`dict`) – HTTP headers. Given headers will overwrite instance-wide headers passed to the constructor. Default: `None` to use the default headers of the [`source`](sources.md#module-sdmx.source). * **key** (`str` or `dict`) – For queries with resource_type=’data’. `str` values are not validated; `dict` values are validated using `make_constraint()`. * **params** (`dict`) – Query parameters. The [SDMX REST web service guidelines](https://github.com/sdmx-twg/sdmx-rest/tree/master/v2_1/ws/rest/docs) describe parameters and allowable values for different queries. params is not validated before the query is executed. * **provider** (`str`) – ID of the agency providing the data or metadata. Default: ID of the [`source`](sources.md#module-sdmx.source) agency. * **resource** ([`MaintainableArtefact`](api/model.md#sdmx.model.common.MaintainableArtefact) subclass) – Object to retrieve. If given, resource_type and resource_id are ignored. ### Request Example ```python # Example for specifying resource_type and resource_id client.get(resource_type='data', resource_id='ABS_QGDP_AUS') # Example for specifying key for data retrieval client.get(resource_type='data', key={'GEO': ['EL', 'ES', 'IE']}) # Example for specifying key as a string client.get(resource_type='data', key='....EL+ES+IE') # Example for specifying optional parameters client.get(resource_type='metadata', resource_id='CL_ABS', params={'references': 'parentsandsiblings'}) ``` ### Response #### Success Response (200) Returns an SDMX [`Message`](#sdmx.message.Message) object or a `requests.Request` object if `dry_run` is True. #### Response Example ```json { "message": "SDMX Message Object or Request Object" } ``` ``` -------------------------------- ### Configure HTTP Caching with SQLite Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Enable and configure HTTP response caching using requests_cache. This example demonstrates how to force requests_cache to use SQLite for storing cached data and set a cache expiration time. ```python from sdmx import Client client = Client( 'ecb', use_requests_cache=True, cache_name='sdmx-cache', expire_after=600, fast_save=True ) ``` -------------------------------- ### Convert SDMX to Pandas and then to Excel Source: https://github.com/khaeru/sdmx/blob/main/doc/howto.md This snippet shows how to read an SDMX file into a pandas DataFrame and then export it to an Excel file. Ensure you have the necessary libraries (sdmx, pandas, openpyxl) installed. ```python msg = sdmx.read_sdmx('data.xml') sdmx.to_pandas(msg).to_excel('data.xlsx') ``` -------------------------------- ### Inspect Code Lists Source: https://github.com/khaeru/sdmx/blob/main/doc/example.md Retrieve and inspect code lists from a StructureMessage. This example shows how to get a specific code list and convert it to a pandas Series for easier examination. ```python from sdmx import Client from sdmx.message import StructureMessage from sdmx.util import to_pandas client = Client("ESTAT") msg = client.get_structure("UNE_RT_A", idtype="dataflow") # Get the code list for dimensions like 'GEO' geo_codelist = msg.get("codelist", "GEO") print(to_pandas(geo_codelist)) # Get the code list for dimensions like 'UNIT' unit_codelist = msg.get("codelist", "UNIT") print(to_pandas(unit_codelist)) ``` -------------------------------- ### Create SDMX Client Source: https://github.com/khaeru/sdmx/blob/main/doc/example.md Instantiate an SDMX client to interact with a specific data provider's web service. This is the first step for making multiple queries. ```python from sdmx import Client client = Client("ESTAT") ``` -------------------------------- ### Example XML Structure Message from UNICEF Source: https://github.com/khaeru/sdmx/blob/main/doc/sources.md This is an example of an XML structure message returned by the UNICEF API. It illustrates the format of the structureID and namespace, and the reference to the dataflow. ```xml ``` -------------------------------- ### Create and Access Key Values Source: https://github.com/khaeru/sdmx/blob/main/doc/api/model.md Demonstrates how to create a Key object with dimension values and access them using dictionary-like syntax. ```python >>> k = Key(foo=1, bar=2) >>> k.values['foo'] 1 >>> k['foo'] 1 ``` -------------------------------- ### sdmx.util.requests.save_response Source: https://github.com/khaeru/sdmx/blob/main/doc/dev.md Stores a response in the cache of a given session. If requests_cache is not installed, this function has no effect. ```APIDOC ## sdmx.util.requests.save_response(session: [Session], method: str, url: str, content: bytes, headers: dict) -> None ### Description Store a response in the cache of session. If `requests_cache` is not available, this has no effect. ### Parameters #### Path Parameters - **session** (Session) - Required - The session object to cache the response in. - **method** (str) - Required - The HTTP method of the request. - **url** (str) - Required - The URL of the request. - **content** (bytes) - Required - The content of the response. - **headers** (dict) - Required - The headers of the response. ``` -------------------------------- ### Query Data Directly via URL Source: https://github.com/khaeru/sdmx/blob/main/doc/sources.md This snippet demonstrates querying data directly from a URL using a generic sdmx Client, bypassing source-specific initialization. This is useful when the source does not offer a dedicated client or for direct file access. ```python c = sdmx.Client() dm = c.get(url="https://sdds.indec.gob.ar/files/data/IND.XML") ``` -------------------------------- ### sdmx.model.v30.RangePeriod Source: https://github.com/khaeru/sdmx/blob/main/doc/api/model.md Represents a time range period in SDMX v3.0, defined by a start and end period. ```APIDOC ## sdmx.model.v30.RangePeriod ### Description Represents a time range period in SDMX v3.0, defined by a start and end period. ### Attributes - **valid_from** (str | None): The date from which the period is valid. - **valid_to** (str | None): The date until which the period is valid. - **start** ([sdmx.model.common.StartPeriod](#sdmx.model.common.StartPeriod) | None): The start period. - **end** ([sdmx.model.common.EndPeriod](#sdmx.model.common.EndPeriod) | None): The end period. ``` -------------------------------- ### sdmx.session.Session Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Custom requests.Session with optional caching. Inherits from requests_cache.CacheMixin if requests_cache is installed, otherwise inherits from requests_cache.RequestsSession. ```APIDOC ## sdmx.session.Session ### Description Custom `requests.Session` with optional caching. If `requests_cache` is installed, this class inherits from `CacheMixin` and caches responses. Otherwise, it inherits only from the `requests_cache`. ### Parameters * **timeout** (`float`) – Timeout in seconds, used for every request. * **kwargs** – These may include: 1. Values for any attributes of `requests.Session`, such as `proxies`, `stream`, or `verify`. These are set on the created Session. 2. Keyword arguments to `CacheMixin` or any `requests_cache` backend. Note that: - Unlike `requests_cache`, you must supply `backend="sqlite"` explicitly; otherwise [`sdmx`](#module-sdmx) uses `backend="memory"`. - These classes will silently ignore any other/unrecognized keyword arguments. ### Raises **TypeError** – if `requests_cache` is *not* installed and any parameters are passed except for timeout. ``` -------------------------------- ### Querying Data in Generic Format Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Demonstrates a basic query to retrieve data in the generic SDMX-ML format. ```python from sdmx import Client client = Client() data_message = client.get(resource_id='EXR', format='xml', params={'startPeriod': '2020-01-01'}) print(data_message.text) ``` -------------------------------- ### ItemScheme Initialization and Item Manipulation Source: https://github.com/khaeru/sdmx/blob/main/doc/api/model.md Demonstrates how to initialize an ItemScheme, add items to it, and access them using various methods including direct attribute access, dictionary-like indexing, and the 'in' operator. ```python >>> foo = ItemScheme(id='foo') >>> bar = Item(id='bar') >>> foo.append(bar) >>> foo >>> (foo.bar is bar) and (foo['bar'] is bar) and (bar in foo) True ``` -------------------------------- ### sdmx.list_sources Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Returns a sorted list of all valid source IDs that can be used to create `Client` instances. ```APIDOC ## sdmx.list_sources() ### Description Return a sorted list of valid source IDs. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) * **List[str]** - A sorted list of valid source IDs. #### Response Example None ``` -------------------------------- ### Get Data Flow Definitions Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Retrieves definitions for all data flows from a chosen source using the sdmx library. The query returns a Message instance. ```python from sdmx import Client client = Client() flow_msg = client.get("dataflow") ``` -------------------------------- ### sdmx.compare.Options Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Options for a comparison. Configures how two SDMX artefacts are compared, including strictness and handling of implied URNs. ```APIDOC ## sdmx.compare.Options ### Description Options for a comparison. Configures how two SDMX artefacts are compared, including strictness and handling of implied URNs. ### Attributes * **allow_implied_urn** (bool) – Objects compare equal even if [`IdentifiableArtefact.urn`](api/model.md#sdmx.model.common.IdentifiableArtefact.urn) is `None` for either or both, so long as the URNs implied by their other attributes—that is, returned by [`sdmx.urn.make()`](#sdmx.urn.make)—are the same. Defaults to `True`. * **base** (Any) – Base object for a recursive comparison. Used internally for memoization/to improve performance. * **log_level** (int) – Level for log messages. Defaults to `0`. * **strict** (bool) – if `True` (the default), then attributes and associated objects must compare exactly equal. If `False`, then `None` values on either side are permitted. Defaults to `True`. * **verbose** (bool) – Continue comparing even after reaching a definitive `False` result. If [`log_level`](#sdmx.compare.Options.log_level) is not set, `verbose = True` implies `log_level = logging.DEBUG`. Defaults to `False`. ### Methods #### log(message: str, level: int = 20) → None Log message on level. level must be at least [`log_level`](#sdmx.compare.Options.log_level). #### visited(obj) → bool Return `True` if obj has already be compared. ``` -------------------------------- ### get Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Retrieves an IdentifiableArtefact from the StructureMessage by its ID or object reference. It supports various string formats for IDs, including exact matches, partial URNs, and full URNs. ```APIDOC ## get(obj_or_id: str | IdentifiableArtefact) -> IdentifiableArtefact | None ### Description Retrieve an IdentifiableArtefact from the StructureMessage using its ID or object reference. This method can handle string inputs that are exact ID matches, partial SDMX URNs, or full SDMX URNs. ### Method get ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **obj_or_id** (`str` or `IdentifiableArtefact`) - Required - The ID of the artefact as a string or an IdentifiableArtefact object. - If an `IdentifiableArtefact` is provided, an object of the same class with a matching ID is returned. - If a `str` is provided, it can be an exact match for an `IdentifiableArtefact.id`, part of an SDMX URN (e.g., “FOO(1.2.3)”), or a full SDMX URN. ### Returns - [`IdentifiableArtefact`](api/model.md#sdmx.model.common.IdentifiableArtefact) - The retrieved IdentifiableArtefact or None if no match is found. ### Raises - **ValueError** – If there are two or more objects with the same obj_or_id (e.g., two objects of different classes, or two objects of the same class with different maintainer or version). ### Request Example None provided in source. ### Response #### Success Response (200) - **IdentifiableArtefact** - The retrieved artefact. #### Response Example None provided in source. ``` -------------------------------- ### Query Data Set with Key and Time Period Source: https://github.com/khaeru/sdmx/blob/main/doc/example.md Download a data set for specific countries (Greece, Ireland, Spain) and a specified time period. This uses the 'GEO' dimension key and the 'startPeriod' query parameter. ```python from sdmx import Client from sdmx.message import DataMessage client = Client("ESTAT") data_key = { "geo": ["EL", "IE", "ES"], "age": "Y15-74", "sex": "T", "unit": "PC_ACT", "TIME_PERIOD": "2020" } dm = client.get_data("UNE_RT_A", key=data_key, params={"startPeriod": "2020"}) assert isinstance(dm, DataMessage) ``` -------------------------------- ### Preview Data and Count Series Keys Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Use preview_data to get a list of SeriesKeys for a given flow_id. The length of this list can be used to count the total number of series. ```python keys = sdmx.Client('PROVIDER').preview_data('flow') len(keys) ``` -------------------------------- ### Create Key Instance Source: https://github.com/khaeru/sdmx/blob/main/doc/api/model.md Creates an instance of a Key class (e.g., Key, SeriesKey, GroupKey) using provided values. Can optionally extend with missing dimensions. ```python key = dsd.make_key(sdmx.model.common.Key, {'dim1': 'val1', 'dim2': 'val2'}) ``` -------------------------------- ### Select Cross-Section using Pandas xs() Source: https://github.com/khaeru/sdmx/blob/main/doc/example.md Use pandas' `xs()` method to select a cross-section of the data based on specific dimension values. This example selects data for 'geo' dimension. ```python from sdmx import Client from sdmx.message import DataMessage from sdmx.util import to_pandas client = Client("ESTAT") data_key = { "geo": ["EL", "IE", "ES"], "age": "Y15-74", "sex": "T", "unit": "PC_ACT", "TIME_PERIOD": "2020" } dm = client.get_data("UNE_RT_A", key=data_key, params={"startPeriod": "2020"}) data = to_pandas(dm) # Select data for Ireland ('IE') from the 'geo' dimension print(data.xs("IE", level="geo")) ``` -------------------------------- ### Read SDMX from Local File Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Use sdmx.read_sdmx to load SDMX messages from local files. Ensure the file path is correctly specified. ```python from sdmx.testing import SpecimenCollection specimen = SpecimenCollection("/path/to/sdmx-test-data") with specimen("ECB_EXR/ng-ts.xml") as f: sdmx.read_sdmx(f) ``` -------------------------------- ### Record HTTP Responses for Testing Source: https://github.com/khaeru/sdmx/blob/main/doc/dev.md Use requests_cache to record HTTP responses from SDMX-REST web services for testing purposes. This example shows how to set up a CachedSession and make a client request to record its response. ```python from requests_cache import CachedSession from sdmx import Client session = CachedSession( "./recorded", # or other path to sdmx-test-data/recorded/ backend="filesystem", serializer="json", ) # Exactly the client and request to be used in a test/cached client = sdmx.Client("ISTAT", session=session) client.dataflow("47_850", params={"references": "datastructure"}) ``` -------------------------------- ### sdmx.model.common.BaseContentConstraint Source: https://github.com/khaeru/sdmx/blob/main/doc/api/model.md Abstract base class for SDMX 2.1 and 3.0 ContentConstraints. ```APIDOC ## sdmx.model.common.BaseContentConstraint ### Description Abstract base class for SDMX 2.1 and 3.0 ContentConstraints. ### Class Signature ```python class BaseContentConstraint ``` ### Attributes This class does not explicitly define attributes in the provided source, but serves as an abstract base for content constraint objects. ``` -------------------------------- ### Select Specific Data Subset Source: https://github.com/khaeru/sdmx/blob/main/doc/example.md Select a specific subset of the data based on dimension values. This example filters for aggregate unemployment rates across ages and sexes, expressed as a percentage of the active population. ```python from sdmx import Client from sdmx.message import DataMessage from sdmx.util import to_pandas client = Client("ESTAT") data_key = { "geo": ["EL", "IE", "ES"], "age": "Y15-74", "sex": "T", "unit": "PC_ACT", "TIME_PERIOD": "2020" } dm = client.get_data("UNE_RT_A", key=data_key, params={"startPeriod": "2020"}) data = to_pandas(dm) # Select aggregate unemployment rates subset = data.loc[("Y15-74", "T", "PC_ACT"), :] print(subset) ``` -------------------------------- ### Converting Daily Exchange Rate Data to Pandas DataFrame Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Demonstrates how to select only daily data from a dataset and convert it into a pandas DataFrame using the to_pandas() function. ```python from sdmx import Client from sdmx.util import to_pandas client = Client() dsd = client.get(resource_id='EXR', resource_type='datastructure') data_message = client.get(resource_id='EXR', dsd=dsd, params={'startPeriod': '2020-01-01'}) # Select only daily data series daily_data = [series for series in data_message.series if series.FREQ == 'D'] df = to_pandas(data_message, series_keys=daily_data) print(df.head()) ``` -------------------------------- ### sdmx.urn.make Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Creates an SDMX URN for a given object. ```APIDOC ## sdmx.urn.make ### Description Create an SDMX URN for obj. If obj is not [`MaintainableArtefact`](api/model.md#sdmx.model.common.MaintainableArtefact), then maintainable_parent must be supplied in order to construct the URN. If kwargs are supplied, they must be fields/attributes of [`URN`](#sdmx.urn.URN), and override values derived from obj and/or maintainable_parent. ### Returns String representation of the URN. ### Return type `str` ``` -------------------------------- ### Expand SDMX URN Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Use this function to get the full URN for a given value. It accepts either a partial URN or a full URN and returns the complete URN string. If the input is not a URN, it is returned unchanged. ```python >>> expand("Code=BAZ:FOO(1.2.3).BAR") "urn:sdmx:org.sdmx.infomodel.codelist.Code=BAZ:FOO(1.2.3).BAR" ``` -------------------------------- ### Build SDMX-REST API v2.1.0 URLs Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Utility class for constructing SDMX-REST API v2.1.0 URLs. It provides methods to handle specific parameters for different endpoint types like data, metadata, and structure. ```python class sdmx.rest.v30.URL(source: [sdmx.source.Source](sources.md#sdmx.source.Source), resource_type: [Resource](#sdmx.Resource), **kwargs) ``` -------------------------------- ### Handle URL Parameters for Registration Endpoints Source: https://github.com/khaeru/sdmx/blob/main/doc/api.md Specific method within the URL class to manage parameters tailored for registration endpoints in the SDMX-REST API. ```python handle_registration() ``` -------------------------------- ### Query Data from AR1 Source Source: https://github.com/khaeru/sdmx/blob/main/doc/sources.md This snippet shows how to query data from the AR1 source using its specific resource ID. It demonstrates using a Client initialized with the source ID. ```python c = sdmx.Client("AR1") # The URL https://sdds.indec.gob.ar/files/data/IND.XML dm = c.data("IND.XML") ``` -------------------------------- ### Query Data from a Dataflow Source: https://github.com/khaeru/sdmx/blob/main/doc/walkthrough.md Initiates a data query for a dataflow using the Client.get() method with resource_type set to 'data'. ```python data_msg = client.get("data", dataflow="EXR") ``` -------------------------------- ### Import Annotation from sdmx.model.v21 Source: https://github.com/khaeru/sdmx/blob/main/doc/whatsnew.md In v2.22.0, Annotation should be imported from sdmx.model.v21. This snippet shows the new way. ```python from sdmx.model.v21 import Annotation a = Annotation(id="FOO", ...) ``` -------------------------------- ### Import Annotation from sdmx.model.common Source: https://github.com/khaeru/sdmx/blob/main/doc/whatsnew.md Before v2.22.0, Annotation was imported from sdmx.model.common. This snippet shows the old way. ```python from sdmx.model.common import Annotation a = Annotation(id="FOO", ...) ``` -------------------------------- ### Run SDMX Source Tests Source: https://github.com/khaeru/sdmx/blob/main/doc/install.md Run the sdmx tests, including those that involve retrieving data over a network connection. This is done using the '-m source' flag with pytest. ```bash pytest -m source ```