{ "cells": [ { "cell_type": "markdown", "id": "92475c69", "metadata": {}, "source": [ "# Python API Example - Gas Transit Costs\n", "\n", "This guide is designed to provide an example of how to access the Spark API:\n", "- The path to your client credentials is the only input needed to run this script (just before Section 2)\n", "- This script has been designed to display the raw outputs of requests from the API, and then shows you how to format those outputs to enable easy reading and analysis\n", "- This script can be copied and pasted by customers for quick use of the API\n", "\n", "__N.B. This guide is just for Gas Transit data. If you're looking for other API data products (such as contract prices, Freight routes or Netbacks), please refer to their according code example files.__ " ] }, { "cell_type": "markdown", "id": "fc7443de", "metadata": {}, "source": [ "### 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: https://www.sparkcommodities.com/api/request/access.html" ] }, { "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": 60, "id": "fe759439", "metadata": {}, "outputs": [], "source": [ "import json\n", "import os\n", "import sys\n", "import numpy as np\n", "from base64 import b64encode\n", "from pprint import pprint\n", "from urllib.parse import urljoin\n", "import pandas as pd\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", "# Defining functions for API request\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", " \"\"\"\n", " OAuth2 authentication requires a POST request with client credentials before accessing the API. \n", " This POST request will return an Access Token which will be used for the API GET request.\n", " \"\"\"\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", " print(url)\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", "\n", " # HTTP POST 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", " print(status)\n", "\n", " # The server must return HTTP 201. 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", " 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` and `scopes` 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\": b64encode(payload).decode(),\n", " \"Accept\": \"application/json\",\n", " \"Content-Type\": \"application/json\",\n", " }\n", " body = {\n", " \"grantType\": \"clientCredentials\",\n", " \"scopes\": \"read:netbacks,read:access,read:prices,read:routes\",\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\"]" ] }, { "cell_type": "markdown", "id": "a51e1ef0", "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. Please refer to the API documentation if you have not dowloaded them already. Instructions for downloading your credentials can be found here:\n", "\n", "https://www.sparkcommodities.com/api/introduction.html\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0817250f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ">>>> Found credentials!\n", ">>>> Client_id=01c23590-ef6c-4a36-8237-c89c3f1a3b2a, client_secret=80763****\n", ">>>> Successfully fetched an access token eyJhb****, valid 604799 seconds.\n" ] } ], "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" ] }, { "cell_type": "markdown", "id": "bf7d9183", "metadata": {}, "source": [ "# 2. Reference Data\n", "\n", "Here we fetch the relevant reference data for the endpoint - this is a list of all available transit route options available on the endpoint. Countries for each hub are also included for easy reference." ] }, { "cell_type": "code", "execution_count": 62, "id": "71c883c6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "v1.0/gas/transit/reference-data/\n", "https://api.sparkcommodities.com/v1.0/gas/transit/reference-data/\n", "200\n" ] }, { "data": { "text/html": [ "
| \n", " | Origin | \n", "Destination | \n", "OriginCountry | \n", "DestinationCountry | \n", "
|---|---|---|---|---|
| 0 | \n", "ttf | \n", "nbp | \n", "Netherlands | \n", "United Kingdom | \n", "
| 1 | \n", "nbp | \n", "ttf | \n", "United Kingdom | \n", "Netherlands | \n", "
| 2 | \n", "nbp | \n", "ztp | \n", "United Kingdom | \n", "Belgium | \n", "
| 3 | \n", "ztp | \n", "nbp | \n", "Belgium | \n", "United Kingdom | \n", "
| 4 | \n", "ttf | \n", "the | \n", "Netherlands | \n", "Germany | \n", "
| ... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "
| 66 | \n", "uavtp | \n", "mgp | \n", "Ukraine | \n", "Hungary | \n", "
| 67 | \n", "rovtp | \n", "uavtp | \n", "Romania | \n", "Ukraine | \n", "
| 68 | \n", "uavtp | \n", "rovtp | \n", "Ukraine | \n", "Romania | \n", "
| 69 | \n", "pvb | \n", "ptvtp | \n", "Spain | \n", "Portugal | \n", "
| 70 | \n", "ptvtp | \n", "pvb | \n", "Portugal | \n", "Spain | \n", "
71 rows × 4 columns
\n", "| \n", " | ReleaseDate | \n", "Origin | \n", "Destination | \n", "Type | \n", "Product | \n", "DeliveryMonth | \n", "DeliveryMonthName | \n", "DeliveryMonthIndex | \n", "ExitCapacity | \n", "ExitVariable | \n", "EntryCapacity | \n", "EntryVariable | \n", "ICCapacity | \n", "ICVariable | \n", "TotalCapacity | \n", "TotalVariable | \n", "TotalTransitCost | \n", "Unit | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", "2026-04-01 | \n", "atvtp | \n", "mgp | \n", "firm | \n", "annual | \n", "2026-05-01 | \n", "May26 | \n", "M+1 | \n", "0.453 | \n", "0.120 | \n", "0.380 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "0.833 | \n", "0.120 | \n", "0.953 | \n", "eur-per-mwh | \n", "
| 1 | \n", "2026-04-01 | \n", "atvtp | \n", "mgp | \n", "firm | \n", "annual | \n", "2026-06-01 | \n", "Jun26 | \n", "M+2 | \n", "0.453 | \n", "0.120 | \n", "0.380 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "0.833 | \n", "0.120 | \n", "0.953 | \n", "eur-per-mwh | \n", "
| 2 | \n", "2026-04-01 | \n", "atvtp | \n", "mgp | \n", "firm | \n", "annual | \n", "2026-07-01 | \n", "Jul26 | \n", "M+3 | \n", "0.453 | \n", "0.120 | \n", "0.380 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "0.833 | \n", "0.120 | \n", "0.953 | \n", "eur-per-mwh | \n", "
| 3 | \n", "2026-04-01 | \n", "atvtp | \n", "mgp | \n", "firm | \n", "annual | \n", "2026-08-01 | \n", "Aug26 | \n", "M+4 | \n", "0.453 | \n", "0.120 | \n", "0.380 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "0.833 | \n", "0.120 | \n", "0.953 | \n", "eur-per-mwh | \n", "
| 4 | \n", "2026-04-01 | \n", "atvtp | \n", "mgp | \n", "firm | \n", "annual | \n", "2026-09-01 | \n", "Sep26 | \n", "M+5 | \n", "0.453 | \n", "0.120 | \n", "0.380 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "0.833 | \n", "0.120 | \n", "0.953 | \n", "eur-per-mwh | \n", "
| ... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "
| 167707 | \n", "2026-05-27 | \n", "ztp | \n", "ttf | \n", "interruptible | \n", "quarterly | \n", "2027-01-01 | \n", "Jan27 | \n", "M+8 | \n", "0.269 | \n", "0.036 | \n", "1.141 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "1.410 | \n", "0.036 | \n", "1.446 | \n", "eur-per-mwh | \n", "
| 167708 | \n", "2026-05-27 | \n", "ztp | \n", "ttf | \n", "interruptible | \n", "quarterly | \n", "2027-02-01 | \n", "Feb27 | \n", "M+9 | \n", "0.269 | \n", "0.036 | \n", "1.141 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "1.410 | \n", "0.036 | \n", "1.446 | \n", "eur-per-mwh | \n", "
| 167709 | \n", "2026-05-27 | \n", "ztp | \n", "ttf | \n", "interruptible | \n", "quarterly | \n", "2027-03-01 | \n", "Mar27 | \n", "M+10 | \n", "0.269 | \n", "0.034 | \n", "1.141 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "1.410 | \n", "0.034 | \n", "1.444 | \n", "eur-per-mwh | \n", "
| 167710 | \n", "2026-05-27 | \n", "ztp | \n", "ttf | \n", "interruptible | \n", "quarterly | \n", "2027-04-01 | \n", "Apr27 | \n", "M+11 | \n", "0.123 | \n", "0.030 | \n", "0.611 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "0.734 | \n", "0.030 | \n", "0.764 | \n", "eur-per-mwh | \n", "
| 167711 | \n", "2026-05-27 | \n", "ztp | \n", "ttf | \n", "interruptible | \n", "quarterly | \n", "2027-05-01 | \n", "May27 | \n", "M+12 | \n", "0.123 | \n", "0.028 | \n", "0.611 | \n", "0.0 | \n", "NaN | \n", "NaN | \n", "0.734 | \n", "0.028 | \n", "0.762 | \n", "eur-per-mwh | \n", "
167712 rows × 18 columns
\n", "