Skip to main content

Guide: Migrating from REST to GraphQL

With the release of our new GraphQL-based API, we're excited to offer a more flexible and powerful way to access bunker price data. If you've been using our old REST API at api.tideform.io/v2/docs, this guide will walk you through migrating to the new system, demonstrating how you can make these queries not only with web calls but also using Python, NodeJS, and C#.

Why Migrate to GraphQL?

GraphQL offers several advantages over the traditional REST architecture, including:

  1. Flexible Endpoint: Unlike REST, where you only have the predefined uses case endpoints, GraphQL consolidates everything into a flexible endpoint, supporting nested and multi-resource queries.
  2. More Efficient Queries: In REST, you often over-fetch or under-fetch data, leading to multiple requests for what you need. With GraphQL, you define exactly the structure of your request and receive only the necessary fields.
  3. Advanced Queries: GraphQL allows you to query related data in one go, such as fetching multiple fuel grades for a single port, but also digging deeper into the data relationships.

Migrating from the Old REST API to GraphQL

Example 1: Fetching the Latest Price for a Specific Port and Fuel Grade

REST API Request Example:

GET /v2/bxprices

This request fetched the latest prices for a prespecified list of ports and fuel grades.

In GraphQL:

In GraphQL, you can get spot prices with a more structured query:

query portspot {
port(id: "SGSIN") {
coordinates {
latitude
longitude
}
fuelPortProfile(fuelGradeId: "VLSFO") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
}
}

In this query:

• We specify the port by ID ("SGSIN" for Singapore), that is based on UN/LOCODE code • Inside the port data, we fetch the profile for the fuel grade VLSFO. • The query delivers the latest price, including the published date and price, along with other information like the currency, source, and name.

Example 2: Querying Multiple Fuel Grades for the Same Port

With GraphQL, you can request data for those fuel grades you want in a single request:

query portspot {
port(id: "SGSIN") {
coordinates {
latitude
longitude
}
mgo: fuelPortProfile(fuelGradeId: "MGO") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
vlsfo: fuelPortProfile(fuelGradeId: "VLSFO") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
}
}

Example 3: Fetching the Latest Price for multiple Ports and Fuel Grades

query portspot {
portsByIds(
ids: [
"SGSIN" # Singapore
"AEFJR" # Al Fujayrah
"NLRTM" # Rotterdam
"GIGIB" # Gibraltar
"USLAX" # Los Angeles
]
) {
id
name
mgo: fuelPortProfile(fuelGradeId: "MGO") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
vlsfo: fuelPortProfile(fuelGradeId: "VLSFO") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
}
}

Implementation in Different Languages

In addition to performing these queries through web calls, you can also interact with the GraphQL API using popular programming languages like Python, NodeJS, and C#. Let's explore how to make these queries in each language.

All examples below include OAuth2 authentication using the Client Credentials flow. See the Authentication guide for details on how to create and manage your OAuth2 clients.

Python Example

In Python, you can use the requests library to send the GraphQL query.

import requests

# OAuth2 authentication - obtain an access token
token_url = "https://auth.nexusdigit.al/oauth2/token"
token_data = {
"grant_type": "client_credentials",
"client_id": "your-client-id",
"client_secret": "your-client-secret",
}
token_response = requests.post(token_url, data=token_data)
access_token = token_response.json()["access_token"]

# GraphQL query
url = "https://api.tideform.io/graphql"
query = """
query portspot {
port(id: "SGSIN") {
coordinates {
latitude
longitude
}
fuelPortProfile(fuelGradeId: "VLSFO") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
}
}
"""

response = requests.post(
url,
json={"query": query},
headers={"Authorization": f"Bearer {access_token}"},
)
print(response.json())

This Python script:

• Obtains an OAuth2 access token using the Client Credentials flow. • Sends an authenticated POST request with the GraphQL query in JSON format. • Fetches the latest price for VLSFO fuel grade in Singapore.

NodeJS Example

In NodeJS (v18+), you can use the built-in fetch API to send the GraphQL query.

async function main() {
// OAuth2 authentication - obtain an access token
const params = new URLSearchParams();
params.set("grant_type", "client_credentials");
params.set("client_id", "your-client-id");
params.set("client_secret", "your-client-secret");

const tokenResponse = await fetch(
"https://auth.nexusdigit.al/oauth2/token",
{
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params.toString(),
}
);
const { access_token } = await tokenResponse.json();

// GraphQL query
const query = `
query portspot {
port(id: "SGSIN") {
coordinates {
latitude
longitude
}
fuelPortProfile(fuelGradeId: "VLSFO") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
}
}`;

const response = await fetch("https://api.tideform.io/graphql", {
method: "POST",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ query }),
});

const data = await response.json();
console.log(data);
}

main();

This NodeJS script:

• Obtains an OAuth2 access token using the Client Credentials flow. • Sends an authenticated POST request with the GraphQL query using the built-in fetch API. • Logs the response, which includes the latest price data for VLSFO fuel in Singapore.

C# Example

In C#, you can use the HttpClient class to make the GraphQL query.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
private static readonly HttpClient client = new HttpClient();

static async Task Main(string[] args)
{
// OAuth2 authentication - obtain an access token
var tokenRequest = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", "your-client-id"),
new KeyValuePair<string, string>("client_secret", "your-client-secret")
});

var tokenResponse = await client.PostAsync(
"https://auth.nexusdigit.al/oauth2/token",
tokenRequest
);
var tokenJson = JsonSerializer.Deserialize<JsonElement>(
await tokenResponse.Content.ReadAsStringAsync()
);
var accessToken = tokenJson.GetProperty("access_token").GetString();

// GraphQL query
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

var query = @"query portspot {
port(id: ""SGSIN"") {
coordinates {
latitude
longitude
}
fuelPortProfile(fuelGradeId: ""VLSFO"") {
spot {
currency
sourceName
source
name
latestPrice {
publishedDate
price
}
}
}
}
}";

var response = await client.PostAsync(
"https://api.tideform.io/graphql",
new StringContent(
JsonSerializer.Serialize(new { query }),
Encoding.UTF8,
"application/json"
)
);

var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}

This C# code:

• Obtains an OAuth2 access token using the Client Credentials flow. • Uses HttpClient to send an authenticated POST request with the GraphQL query. • Fetches and prints the latest bunker price for VLSFO fuel grade in Singapore.

Steps for Migrating to GraphQL

  1. Understand Your Current REST Queries: Review the endpoints and data fields you currently use.
  2. Set Up Authentication: Create an OAuth2 client in the Portal under "My Organization" and obtain your Client ID and Client Secret. See the Authentication guide for details.
  3. Translate to GraphQL: Convert each of your REST requests into a GraphQL query by specifying the exact fields you need. Start simple—fetch just one resource, then move on to more complex queries.
  4. Use the Appropriate Programming Language: Whether you use Python, NodeJS, or C#, it's easy to interact with the new GraphQL API and fetch the exact data you need.

Benefits of Using Our GraphQL API

• Customization: Request exactly what you need and no more. • Speed: Fewer requests lead to faster response times, reducing the overhead of managing multiple REST calls. • Scalability: Whether you need data for one port or many, GraphQL scales efficiently to your needs.

Getting Started

Visit our GraphQL API documentation to dive deeper into the available queries and options. You'll find examples, schemas, and all the details you need to make a smooth transition.