Integration Examples

This article provides example code in C# to achieve the following:

  • Authenticate with username and password and retrieve a token.

  • Use the token to;

    • Retrieve the first 10 visible vessels

    • Retrieve the first 10 visible files linked to the first vessel retrieved previously.

    • Get the contents of the first file returned in the previous request and if it is a PDF file, save it to the user device.

Each code example adds additional functionality to the request and they should be studied in order to understand the correct order that each endpoint should be queried.

Authenticating Get Visible Vessels Get Files Uploaded Against Vessel Get File Contents

This code example will pass the username and password for your API-enabled account to the authentication endpoint and retrieve your authorisation token into the token variable.

This token should then be passed in the header of all subsequent requests.

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
	static async Task Main()
	{
		using var client = new HttpClient();
		
		// Set common headers for all requests
		client.DefaultRequestHeaders.Add("Accept", "application/json");
		client.DefaultRequestHeaders.Add("api-version", "1.0");
		
		// Authenticate and retrieve token
		var content = new FormUrlEncodedContent(new Dictionary<string, string>
		{
			["username"] = "your_username",
			["password"] = "your_password",
			["grant_type"] = "password"
		});
		var response = await client.PostAsync("https://uat-core-hub-api.misvetting.com/token", content);
		response.EnsureSuccessStatusCode();
		var responseContent = await response.Content.ReadAsStringAsync();
		var token = JsonSerializer.Deserialize<JsonElement>(responseContent)
									.GetProperty("access_token")
									.GetString();
		Console.WriteLine($"Token: {token}");
	}
}

This example sets the header Authorization using the token obtained in the first step, and retrieves the first 10 Vessels returned by Hub.

The pageNumber and pageSize integers are always mandatory where supported by the relevant endpoint.


using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
    static async Task Main()
    {
        using var client = new HttpClient();
				
		// Set common headers for all requests
		client.DefaultRequestHeaders.Add("Accept", "application/json");
		client.DefaultRequestHeaders.Add("api-version", "1.0");
        // Authenticate and retrieve the token
        var content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["username"] = "your_username",
            ["password"] = "your_password",
            ["grant_type"] = "password"
        });
        var response = await client.PostAsync("https://uat-core-hub-api.misvetting.com/token", content);
        response.EnsureSuccessStatusCode();
        var responseContent = await response.Content.ReadAsStringAsync();
        var token = JsonSerializer.Deserialize<JsonElement>(responseContent)
                                    .GetProperty("access_token")
                                    .GetString();
        Console.WriteLine("Token retrieved successfully.");
        // Set authorization header
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        // Retrieve the list of vessels with pagination parameters
        int pageNumber = 1;
        int pageSize = 10;
        string vesselsUrl = $"https://uat-core-hub-api.misvetting.com/v1/Vessels?paginationOptions.pageNumber={pageNumber}&paginationOptions.pageSize={pageSize}";
        var vesselsResponse = await client.GetAsync(vesselsUrl);
        vesselsResponse.EnsureSuccessStatusCode();
        var vesselsContent = await vesselsResponse.Content.ReadAsStringAsync();
        Console.WriteLine("Vessels:");
        Console.WriteLine(vesselsContent);
}

This example extracts the value of the vessel_MarineDataHubIdentifier parameter for the first Vessel returned by the previous example and passes it to the /api/Documents endpoint.

This retrieves a list of all visible documents linked to that Vessel.


using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
    static async Task Main()
    {
        using var client = new HttpClient();
				
		// Set common headers for all requests
		client.DefaultRequestHeaders.Add("Accept", "application/json");
		client.DefaultRequestHeaders.Add("api-version", "1.0");
        // Authenticate and retrieve the token
        var content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["username"] = "your_username",
            ["password"] = "your_password",
            ["grant_type"] = "password"
        });
        var response = await client.PostAsync("https://uat-core-hub-api.misvetting.com/token", content);
        response.EnsureSuccessStatusCode();
        var responseContent = await response.Content.ReadAsStringAsync();
        var token = JsonSerializer.Deserialize<JsonElement>(responseContent)
                                    .GetProperty("access_token")
                                    .GetString();
        Console.WriteLine("Token retrieved successfully.");
        // Set authorization header
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        // Retrieve the list of vessels with pagination parameters
        int pageNumber = 1;
        int pageSize = 10;
        string vesselsUrl = $"https://uat-core-hub-api.misvetting.com/v1/Vessels?paginationOptions.pageNumber={pageNumber}&paginationOptions.pageSize={pageSize}";
        var vesselsResponse = await client.GetAsync(vesselsUrl);
        vesselsResponse.EnsureSuccessStatusCode();
        var vesselsContent = await vesselsResponse.Content.ReadAsStringAsync();
        Console.WriteLine("Vessels:");
        Console.WriteLine(vesselsContent);
        // Parse the vessel response and extract vessel_MarineDataHubIdentifier
        var vesselsJson = JsonSerializer.Deserialize<JsonElement>(vesselsContent);
        if (vesselsJson.GetArrayLength() > 0)
        {
            var firstVessel = vesselsJson[0];
            var vesselId = firstVessel.GetProperty("vessel_MarineDataHubIdentifier").GetString();
            Console.WriteLine($"Retrieving documents for Vessel ID: {vesselId}");
            // Retrieve documents for the specific vessel
            string documentsUrl = $"https://uat-core-hub-api.misvetting.com/v1/Documents?vessel_MarineDataHubIdentifier={vesselId}";
            var documentsResponse = await client.GetAsync(documentsUrl);
            documentsResponse.EnsureSuccessStatusCode();
            var documentsContent = await documentsResponse.Content.ReadAsStringAsync();
            Console.WriteLine("Documents:");
            Console.WriteLine(documentsContent);
        }
        else
        {
            Console.WriteLine("No vessels found.");
        }
    }
}

This example retrieves the base64 contents of the first file returned by the previous example and determines its file type.

If it is a PDF, the file is then saved to the user's device.

Ensure to import the System.IO namespace to save the file.


using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using System.IO;
class Program
{
    static async Task Main()
    {
        using var client = new HttpClient();
				
		// Set common headers for all requests
		client.DefaultRequestHeaders.Add("Accept", "application/json");
		client.DefaultRequestHeaders.Add("api-version", "1.0");
        // Authenticate and retrieve the token
        var content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["username"] = "your_username",
            ["password"] = "your_password",
            ["grant_type"] = "password"
        });
        var response = await client.PostAsync("https://uat-core-hub-api.misvetting.com/token", content);
        response.EnsureSuccessStatusCode();
        var responseContent = await response.Content.ReadAsStringAsync();
        var token = JsonSerializer.Deserialize<JsonElement>(responseContent)
                                    .GetProperty("access_token")
                                    .GetString();
        Console.WriteLine("Token retrieved successfully.");
        // Set authorization header
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        // Retrieve the list of vessels with pagination parameters
        int pageNumber = 1;
        int pageSize = 10;
        string vesselsUrl = $"https://uat-core-hub-api.misvetting.com/v1/Vessels?paginationOptions.pageNumber={pageNumber}&paginationOptions.pageSize={pageSize}";
        var vesselsResponse = await client.GetAsync(vesselsUrl);
        vesselsResponse.EnsureSuccessStatusCode();
        var vesselsContent = await vesselsResponse.Content.ReadAsStringAsync();
        Console.WriteLine("Vessels:");
        Console.WriteLine(vesselsContent);
        // Parse the vessel response and extract vessel_MarineDataHubIdentifier
        var vesselsJson = JsonSerializer.Deserialize<JsonElement>(vesselsContent);
        if (vesselsJson.GetArrayLength() > 0)
        {
            var firstVessel = vesselsJson[0];
            var vesselId = firstVessel.GetProperty("vessel_MarineDataHubIdentifier").GetString();
            Console.WriteLine($"Retrieving documents for Vessel ID: {vesselId}");
            // Retrieve documents for the specific vessel
            string documentsUrl = $"https://uat-core-hub-api.misvetting.com/v1/Documents?vessel_MarineDataHubIdentifier={vesselId}";
            var documentsResponse = await client.GetAsync(documentsUrl);
            documentsResponse.EnsureSuccessStatusCode();
            var documentsContent = await documentsResponse.Content.ReadAsStringAsync();
            Console.WriteLine("Documents:");
            Console.WriteLine(documentsContent);
            // Parse the documents response and extract fileId
            var documentsJson = JsonSerializer.Deserialize<JsonElement>(documentsContent);
            if (documentsJson.GetArrayLength() > 0)
            {
                var firstDocument = documentsJson[0];
                var fileId = firstDocument.GetProperty("fileID").GetString();
                Console.WriteLine($"Retrieving file contents for File ID: {fileId}");
                // Retrieve file contents for the specific file
                string fileContentsUrl = $"https://uat-core-hub-api.misvetting.com/v1/Files/{fileId}/Contents";
                var fileResponse = await client.GetAsync(fileContentsUrl);
                fileResponse.EnsureSuccessStatusCode();
                var fileContentBase64 = await fileResponse.Content.ReadAsStringAsync();
                Console.WriteLine("File Contents Retrieved.");
                // Convert base64 string to byte array
                byte[] fileBytes = Convert.FromBase64String(fileContentBase64);
                
                // Detect file type by checking the file signature (magic number)
                string fileType = GetFileType(fileBytes);
                Console.WriteLine($"Detected File Type: {fileType}");
                if (fileType == "PDF")
                {
                  string filePath = $"{fileId}.pdf";
                  File.WriteAllBytes(filePath, fileBytes);
                  Console.WriteLine($"PDF file saved as {filePath}");
                }
                else
                {
                  Console.WriteLine("Unsupported file type, file not saved.");
                }
                static string GetFileType(byte[] fileBytes)
                {
                  // Check for PDF signature
                  if (fileBytes.Length >= 4 && fileBytes[0] == 0x25 && fileBytes[1] == 0x50 && fileBytes[2] == 0x44 && fileBytes[3] == 0x46)
                  {
                    return "PDF";
                  }
                  // Add more checks for other file types (e.g., JPEG, PNG, etc.)
                  else if (fileBytes.Length >= 3 && fileBytes[0] == 0xFF && fileBytes[1] == 0xD8 && fileBytes[2] == 0xFF)
                  {
                    return "JPEG";
                  }
                  else if (fileBytes.Length >= 8 && fileBytes[0] == 0x89 && fileBytes[1] == 0x50 && fileBytes[2] == 0x4E && fileBytes[3] == 0x47)
                  {
                    return "PNG";
                  }
                return "Unknown file type";
                }
                
            }
            else
            {
                Console.WriteLine("No documents found for this vessel.");
            }
        }
        else
        {
            Console.WriteLine("No vessels found.");
        }
    }
}