{ "cells": [ { "cell_type": "markdown", "id": "92475c69", "metadata": {}, "source": [ "# Python API Example - LNG Hubs (Cargo) API\n", "## Calling the latest & historical Hubs FOB & DES posts\n", "\n", "Here we call currently Active & Inactive (i.e. Historical) LNG Hubs FOB & DES posts for all available regions\n", "\n", "### Have any questions?\n", "\n", "If you have any questions regarding our API, or need help accessing specific datasets, please contact us at:\n", "\n", "__data@sparkcommodities.com__\n", "\n", "or refer to our API website for more information about this endpoint:\n", "https://www.sparkcommodities.com/api/" ] }, { "cell_type": "markdown", "id": "c5716130", "metadata": {}, "source": [ "## 1. Importing Data\n", "\n", "Here we define the functions that allow us to retrieve the valid credentials to access the Spark API.\n", "\n", "__This section can remain unchanged for most Spark API users.__" ] }, { "cell_type": "code", "execution_count": null, "id": "33fb0640", "metadata": {}, "outputs": [], "source": [ "import json\n", "import os\n", "import sys\n", "import pandas as pd\n", "import numpy as np\n", "from base64 import b64encode\n", "from pprint import pprint\n", "from urllib.parse import urljoin\n", "from datetime import datetime\n", "\n", "\n", "try:\n", " from urllib import request, parse\n", " from urllib.error import HTTPError\n", "except ImportError:\n", " raise RuntimeError(\"Python 3 required\")\n", "\n", "\n", "API_BASE_URL = \"https://api.sparkcommodities.com\"\n", "\n", "\n", "def retrieve_credentials(file_path=None):\n", " \"\"\"\n", " Find credentials either by reading the client_credentials file or reading\n", " environment variables\n", " \"\"\"\n", " if file_path is None:\n", " client_id = os.getenv(\"SPARK_CLIENT_ID\")\n", " client_secret = os.getenv(\"SPARK_CLIENT_SECRET\")\n", " if not client_id or not client_secret:\n", " raise RuntimeError(\n", " \"SPARK_CLIENT_ID and SPARK_CLIENT_SECRET environment vars required\"\n", " )\n", " else:\n", " # Parse the file\n", " if not os.path.isfile(file_path):\n", " raise RuntimeError(\"The file {} doesn't exist\".format(file_path))\n", "\n", " with open(file_path) as fp:\n", " lines = [l.replace(\"\\n\", \"\") for l in fp.readlines()]\n", "\n", " if lines[0] in (\"clientId,clientSecret\", \"client_id,client_secret\"):\n", " client_id, client_secret = lines[1].split(\",\")\n", " else:\n", " print(\"First line read: '{}'\".format(lines[0]))\n", " raise RuntimeError(\n", " \"The specified file {} doesn't look like to be a Spark API client \"\n", " \"credentials file\".format(file_path)\n", " )\n", "\n", " print(\">>>> Found credentials!\")\n", " print(\n", " \">>>> Client_id={}, client_secret={}****\".format(client_id, client_secret[:5])\n", " )\n", "\n", " return client_id, client_secret\n", "\n", "\n", "def do_api_post_query(uri, body, headers):\n", " url = urljoin(API_BASE_URL, uri)\n", "\n", " data = json.dumps(body).encode(\"utf-8\")\n", "\n", " # HTTP POST request\n", " req = request.Request(url, data=data, headers=headers)\n", " try:\n", " response = request.urlopen(req)\n", " except HTTPError as e:\n", " print(\"HTTP Error: \", e.code)\n", " print(e.read())\n", " sys.exit(1)\n", "\n", " resp_content = response.read()\n", "\n", " # The server must return HTTP 201. Raise an error if this is not the case\n", " assert response.status == 201, resp_content\n", "\n", " # The server returned a JSON response\n", " content = json.loads(resp_content)\n", "\n", " return content\n", "\n", "\n", "def do_api_get_query(uri, access_token, format='json'):\n", " \"\"\"\n", " After receiving an Access Token, we can request information from the API.\n", " \"\"\"\n", " url = urljoin(API_BASE_URL, uri)\n", "\n", " if format == 'json':\n", " headers = {\n", " \"Authorization\": \"Bearer {}\".format(access_token),\n", " \"Accept\": \"application/json\",\n", " }\n", " elif format == 'csv':\n", " headers = {\n", " \"Authorization\": \"Bearer {}\".format(access_token),\n", " \"Accept\": \"text/csv\"\n", " }\n", " else:\n", " raise AttributeError('The format parameter only takes `csv` or `json` as inputs')\n", "\n", " # HTTP GET request\n", " req = request.Request(url, headers=headers)\n", " try:\n", " response = request.urlopen(req)\n", " except HTTPError as e:\n", " print(\"HTTP Error: \", e.code)\n", " print(e.read())\n", " sys.exit(1)\n", "\n", " resp_content = response.read()\n", " #status = response.status\n", "\n", " # The server must return HTTP 200. Raise an error if this is not the case\n", " assert response.status == 200, resp_content\n", "\n", " # Storing response based on requested format\n", " if format == 'json':\n", " content = json.loads(resp_content)\n", " elif format == 'csv':\n", " content = resp_content\n", " \n", "\n", " return content\n", "\n", "\n", "def get_access_token(client_id, client_secret):\n", " \"\"\"\n", " Get a new access_token. Access tokens are the thing that applications use to make\n", " API requests. Access tokens must be kept confidential in storage.\n", "\n", " # Procedure:\n", "\n", " Do a POST query with `grantType` in the body. A basic authorization\n", " HTTP header is required. The \"Basic\" HTTP authentication scheme is defined in\n", " RFC 7617, which transmits credentials as `clientId:clientSecret` pairs, encoded\n", " using base64.\n", " \"\"\"\n", "\n", " # Note: for the sake of this example, we choose to use the Python urllib from the\n", " # standard lib. One should consider using https://requests.readthedocs.io/\n", "\n", " payload = \"{}:{}\".format(client_id, client_secret).encode()\n", " headers = {\n", " \"Authorization\": \"Basic {}\".format(b64encode(payload).decode()),\n", " \"Accept\": \"application/json\",\n", " \"Content-Type\": \"application/json\",\n", " }\n", " body = {\n", " \"grantType\": \"clientCredentials\",\n", " }\n", "\n", " content = do_api_post_query(uri=\"/oauth/token/\", body=body, headers=headers)\n", "\n", " print(\n", " \">>>> Successfully fetched an access token {}****, valid {} seconds.\".format(\n", " content[\"accessToken\"][:5], content[\"expiresIn\"]\n", " )\n", " )\n", "\n", " return content[\"accessToken\"]\n", "\n", "\n" ] }, { "cell_type": "markdown", "id": "fd3171a8", "metadata": {}, "source": [ "## N.B. Credentials\n", "\n", "Here we call the above functions, and input the file path to our credentials.\n", "\n", "N.B. You must have downloaded your client credentials CSV file before proceeding. You can create and download API credentials from the Spark Platform:\n", "\n", "https://app.sparkcommodities.com/data-integrations/api\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "fd7e89bf", "metadata": {}, "outputs": [], "source": [ "# Insert file path to your client credentials here\n", "client_id, client_secret = retrieve_credentials(file_path=\"/tmp/client_credentials.csv\")\n", "\n", "# Authenticate:\n", "access_token = get_access_token(client_id, client_secret)\n", "print(access_token)" ] }, { "cell_type": "markdown", "id": "8fa4f6cd", "metadata": {}, "source": [ "# 2. Reference Data\n", "\n", "Here we fetch the relevant reference data for the endpoint. This includes region and incoterm codes that can be used in the data-fetching functions later in the script" ] }, { "cell_type": "code", "execution_count": null, "id": "5e02319b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "v1.0/lng/hubs/cargo/reference-data/\n" ] }, { "data": { "text/html": [ "
| \n", " | Region | \n", "Incoterm | \n", "SlotType | \n", "
|---|---|---|---|
| 0 | \n", "usg | \n", "fob | \n", "slot-swap | \n", "
| 1 | \n", "usg | \n", "fob | \n", "outright | \n", "
| 2 | \n", "waf | \n", "fob | \n", "slot-swap | \n", "
| 3 | \n", "waf | \n", "fob | \n", "outright | \n", "
| 4 | \n", "meg | \n", "fob | \n", "slot-swap | \n", "
| \n", " | PostID | \n", "Incoterm | \n", "HubRegions | \n", "InterestType | \n", "OrderType | \n", "Status | \n", "PosterOrgName | \n", "ConnectionCount | \n", "TerminalNames | \n", "TerminalsAreHidden | \n", "... | \n", "IndicativePriceIndex | \n", "IndicativePriceIndexedMonth | \n", "IndicativePriceIndexPercentage | \n", "IndicativePriceIndexConstant | \n", "IndicativePriceIsHidden | \n", "OtherInfo | \n", "OtherInfoIsHidden | \n", "PostedAtUTC | \n", "PostValidUntilUTC | \n", "PostLastUpdatedAtUTC | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", "LNG-USG-S-0177 | \n", "fob | \n", "usg | \n", "swap | \n", "offered | \n", "active | \n", "Anonymous | \n", "0 | \n", "Cameron (Liqu.) | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "True | \n", "vol flex | \n", "False | \n", "2026-02-10T20:10:45.773575Z | \n", "2026-02-14T00:00:00Z | \n", "2026-02-10T20:10:45.773666Z | \n", "
| 1 | \n", "LNG-USG-S-0177 | \n", "fob | \n", "usg | \n", "swap | \n", "requested | \n", "active | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Plaquemines,Calcasi... | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "True | \n", "vol flex | \n", "False | \n", "2026-02-10T20:10:45.773575Z | \n", "2026-02-14T00:00:00Z | \n", "2026-02-10T20:10:45.773666Z | \n", "
| 2 | \n", "LNG-USG-S-0178 | \n", "fob | \n", "usg | \n", "swap | \n", "offered | \n", "active | \n", "Anonymous | \n", "0 | \n", "Sabine Pass | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "False | \n", "vol flex | \n", "False | \n", "2026-02-10T20:12:11.088240Z | \n", "2026-02-14T00:00:00Z | \n", "2026-02-10T20:12:11.088325Z | \n", "
3 rows × 34 columns
\n", "| \n", " | PostID | \n", "Incoterm | \n", "HubRegions | \n", "InterestType | \n", "OrderType | \n", "Status | \n", "PosterOrgName | \n", "ConnectionCount | \n", "TerminalNames | \n", "TerminalsAreHidden | \n", "... | \n", "IndicativePriceIndex | \n", "IndicativePriceIndexedMonth | \n", "IndicativePriceIndexPercentage | \n", "IndicativePriceIndexConstant | \n", "IndicativePriceIsHidden | \n", "OtherInfo | \n", "OtherInfoIsHidden | \n", "PostedAtUTC | \n", "PostValidUntilUTC | \n", "PostLastUpdatedAtUTC | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", "LNG-USG-S-0175 | \n", "fob | \n", "usg | \n", "swap | \n", "offered | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Calcasieu Pass | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "True | \n", "NaN | \n", "False | \n", "2026-02-04T14:07:04.756076Z | \n", "2026-02-11T00:00:00Z | \n", "2026-02-11T00:00:06.614503Z | \n", "
| 1 | \n", "LNG-USG-S-0175 | \n", "fob | \n", "usg | \n", "swap | \n", "requested | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Plaquemines,Calcasi... | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "True | \n", "vol flex | \n", "False | \n", "2026-02-04T14:07:04.756076Z | \n", "2026-02-11T00:00:00Z | \n", "2026-02-11T00:00:06.614503Z | \n", "
| 2 | \n", "LNG-NWE-O-0042 | \n", "des | \n", "nwe,swe | \n", "outright | \n", "offer | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Gate,Zeebrugge,Dunkerque,Bilbao,Sines,Sagunto,... | \n", "False | \n", "... | \n", "TTF | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "False | \n", "NaN | \n", "False | \n", "2026-01-30T14:52:48.090799Z | \n", "2026-02-03T18:00:00Z | \n", "2026-02-03T18:00:05.529188Z | \n", "
| 3 | \n", "LNG-USG-O-0056 | \n", "fob | \n", "usg | \n", "outright | \n", "offer | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Plaquemines,Calcasi... | \n", "False | \n", "... | \n", "TTF | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "False | \n", "NaN | \n", "False | \n", "2026-01-29T16:19:57.695064Z | \n", "2026-02-06T17:00:00Z | \n", "2026-02-06T17:00:05.762594Z | \n", "
| 4 | \n", "LNG-USG-S-0170 | \n", "fob | \n", "usg | \n", "swap | \n", "offered | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Calcasieu Pass | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "False | \n", "NaN | \n", "False | \n", "2026-01-29T14:59:16.285599Z | \n", "2026-01-30T17:00:00Z | \n", "2026-01-30T17:00:03.101753Z | \n", "
5 rows × 34 columns
\n", "| \n", " | PostID | \n", "Incoterm | \n", "HubRegions | \n", "InterestType | \n", "OrderType | \n", "Status | \n", "PosterOrgName | \n", "ConnectionCount | \n", "TerminalNames | \n", "TerminalsAreHidden | \n", "... | \n", "IndicativePriceIndex | \n", "IndicativePriceIndexedMonth | \n", "IndicativePriceIndexPercentage | \n", "IndicativePriceIndexConstant | \n", "IndicativePriceIsHidden | \n", "OtherInfo | \n", "OtherInfoIsHidden | \n", "PostedAtUTC | \n", "PostValidUntilUTC | \n", "PostLastUpdatedAtUTC | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", "LNG-USG-S-0175 | \n", "fob | \n", "usg | \n", "swap | \n", "requested | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Plaquemines,Calcasi... | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "True | \n", "vol flex | \n", "False | \n", "2026-02-04T14:07:04.756076Z | \n", "2026-02-11T00:00:00Z | \n", "2026-02-11T00:00:06.614503Z | \n", "
| 1 | \n", "LNG-USG-O-0056 | \n", "fob | \n", "usg | \n", "outright | \n", "offer | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Plaquemines,Calcasi... | \n", "False | \n", "... | \n", "TTF | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "False | \n", "NaN | \n", "False | \n", "2026-01-29T16:19:57.695064Z | \n", "2026-02-06T17:00:00Z | \n", "2026-02-06T17:00:05.762594Z | \n", "
| 2 | \n", "LNG-USG-S-0170 | \n", "fob | \n", "usg,waf | \n", "swap | \n", "requested | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Calcasieu Pass,Free... | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "False | \n", "NaN | \n", "False | \n", "2026-01-29T14:59:16.285599Z | \n", "2026-01-30T17:00:00Z | \n", "2026-01-30T17:00:03.101753Z | \n", "
| 3 | \n", "LNG-USG-S-0169 | \n", "fob | \n", "usg | \n", "swap | \n", "requested | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Plaquemines,Calcasi... | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "False | \n", "NaN | \n", "False | \n", "2026-01-27T18:05:33.520171Z | \n", "2026-02-02T17:00:00Z | \n", "2026-02-02T17:00:02.227684Z | \n", "
| 4 | \n", "LNG-USG-S-0167 | \n", "fob | \n", "usg | \n", "swap | \n", "requested | \n", "expired | \n", "Anonymous | \n", "0 | \n", "Sabine Pass,Corpus Christi,Plaquemines,Calcasi... | \n", "False | \n", "... | \n", "NaN | \n", "NaN | \n", "NaN | \n", "NaN | \n", "False | \n", "NaN | \n", "False | \n", "2026-01-26T15:04:24.117462Z | \n", "2026-01-30T18:00:00Z | \n", "2026-01-30T18:00:01.908710Z | \n", "
5 rows × 34 columns
\n", "