Skip to content

Getting Started with ECGridOS and HTTP Connections

Greg Kolinski edited this page Oct 28, 2022 · 8 revisions

Back To ECGridOS Home


HTTP Get

ECGridOS has endpoints for all API calls using the HTTP Get method. This is typically not use very often as most API calls require you to pass an API-Key or Session ID as a parameter. Since HTTP Get calls have the parameters in the URL we do not recommend this for getting your data. However this can be a beneficial for calls that don't require parameter like the Version() call. This can be used to verify the availability of our service with very little overhead.


HTTP POST

HTTP Post method calls are a common way to access our web service. They are made just like a form request from a browser using the application/x-www-form-urlencoded Content Type. Please note we do not allow multipart/form-data, files are uploaded using a byte array or base64 string. All API endpoints are accessed using HTTPS and all form data is encrypted during transport using industry standard SSL security/certificates. Accessing the ECGridOS web service allows you to customize your use of this web service only implementing the calls you need and providing the freedom to connect using any programming language you want.


Please Note ECGridOS returns XML, which can be used directly or serialized/reserialized in to objects. Several example show this process in the Code section. Use the appropriate method required for the language you are using.

If you are using .NET please see the examples in the Code section. There are full class objects and HTTP Client examples for you to get started. The code examples provided are for reference only and intended to be used as a starting point and example of how you can build the HTTP connection yourself. Please follow your companies policies and practices for software development. Set your own values for request parameters and don't store you passwords/secrets in plain text directly in the code.


The examples below are not production code and not the only way to make the HTTP POST requests. There are many methods and libraries available that can perform this action. Use the appropriate one for your situation and for your companies development practice/policy. Please note this does not cover all programming languages. If you can make a HTTP POST in your language you can use our service.

C#

using System;
using System.Net.Http;
using System.Threading.Tasks;

public async Task<SessionInfo> WhoAmI(string sessionID)
{
	try
	{
		// Post Form Parameters
		var parameters = new Dictionary<string, string> {
			{ "SessionID", sessionID }
		};

		var requestMessage = new HttpRequestMessage
		{
			Method = HttpMethod.Post,
			RequestUri = new Uri($"{_client.BaseAddress}WhoAmI"),
			Content = new FormUrlEncodedContent(parameters)
		};

		using HttpResponseMessage responseHeader = await _client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);
		requestMessage.Dispose();
		if (responseHeader.IsSuccessStatusCode)
		{
			using var responseStream = await responseHeader.Content.ReadAsStreamAsync();
			using StreamReader stream_reader = new StreamReader(responseStream);
			var serializer = new XmlSerializer(typeof(SessionInfo), domain_name);
			return (SessionInfo)serializer.Deserialize(stream_reader);
		}
		else
		{
			using var responseStream = await responseHeader.Content.ReadAsStreamAsync();
			using StreamReader stream_reader = new StreamReader(responseStream);
			string error = await stream_reader.ReadToEndAsync();
			return null;
		}
	}
	catch (Exception ex)
	{
		Console.WriteLine.Error(ex, "Error getting ECGridOS Result.");
		return null;
	}
}

Python

import urllib.request
import urllib.parse
import xml.etree.ElementTree as ElementTree

def WhoAmI(self, apiKey):
	try:
		# Encode and Format the Data Values
		values = {'SessionID': apiKey}
		data = urllib.parse.urlencode(values)
		data = data.encode('utf8')

		# Make Request to ECGrid
		req = urllib.request.Request(self.ecgridi_url_base + "/WhoAmI", data)

		# Get the Response from ECGrid
		resp = urllib.request.urlopen(req)

		# Make Element Tree and Root from Response
		xml_data = ElementTree.ElementTree(ElementTree.fromstring(resp.read()))
		root = xml_data.getroot()

		# Parse the XMl Response to a dictionary
		xml_as_dict = self.make_dict_from_tree(root)
		return xml_as_dict

	except urllib.error.HTTPError as e:
		errorbody = e.read().decode('utf-8')
		if "AccessDenied" in errorbody:
			return {
				'success': False,
				'code': "403",
				'error': {
					'type': "ECGrid Exception",
					'message': "AccessDenied",
					'handler': 'ECGridOS API'
				}
			}

	except Exception as ex:
		return {
				'success': False,
				'code': "500",
				'error': {
					'type': "Unknown",
					'message': ex,
					'handler': 'ECGridOS API'
				}
			}

	return None

Java

import okhttp3.*;

import java.io.IOException;

public class OkHttpExample {

    // one instance, reuse
    private final OkHttpClient httpClient = new OkHttpClient();

    public static void main(String[] args) throws Exception {
        OkHttpExample obj = new OkHttpExample();

        System.out.println("Testing 2 - Send Http POST request");
        obj.sendPost();
    }


	private void sendPost() throws Exception {

		// form parameters
		RequestBody formBody = new FormBody.Builder()
				.add("SessionID", UserAPIKey)
				.build();

		Request request = new Request.Builder()
				.url(ecgridOS_BaseURL.Concat("WhoAmI"))
				.addHeader("User-Agent", "OkHttp Bot")
				.post(formBody)
				.build();

		try (Response response = httpClient.newCall(request).execute()) {
			if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
			// Get response body
			System.out.println(response.body().string());
		}

	}
}

JS

var axios = require('axios');
var convert = require("xml-js");
var FormData = require('form-data');

var data = new FormData();
data.append('SessionID', UserAPIKey);

var config = {
  method: 'post',
  url: ecgridOS_BaseURL + 'WhoAmI',
  headers: { 
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
  console.log(JSON.parse(convert.xml2json(response.data, { compact: true, spaces: 2 })));
})
.catch(function (error) {
  console.log(error);
});

PHP

use \GuzzleHttp\Exception\RequestException;
use \GuzzleHttp\Client;

public static function WhoAmI()
{
	try
	{
		$client = new \GuzzleHttp\Client;
		$promise = $client->requestAsync(
			'POST',
			ecgridos_baseURL.'WhoAmI',
			[
				'form_params' => [
					'sessionID' => api_key
				]
			]
		);
		$response = $promise->wait();

		if ($response->getStatusCode() == 200) 
		{
			$xml_string = $response->getBody()->getContents();
			$xml = simplexml_load_string($xml_string);
			$jsonStr = json_encode($xml);
			$jsonObj = json_decode($jsonStr, true);
			
			return $jsonObj;
		}

		return null; 
	}
	catch(\Exception $e) 
	{ 
		Log::warning("Exception, ECGridClient::WhoAmI()\n$e");
		return null; 
	}
}

Back To ECGridOS Home

Clone this wiki locally