C# call REST client with x-api-key within grasshopper

unhandled
csharp
(P D Siedler) #1

Hi there, I was wondering if anyone has done a REST api call with a x-api-key using a c# component in grasshopper? If yes could you guide me to an example, if no any any idea where to start with this?

Thanks, Phil

1 Like
(Luis Fraguada) #2

Is there a particular API you wish to call?

1 Like
(P D Siedler) #3

Hi, well this is the documentation for the OpenSensors API I wish to call. I have an accoun there and a x-api-key. (opensensors.com)
Thanks for your help!

(Luis Fraguada) #4

This is a simple example calling https://yesno.wtf/api from a c# component in GH:

var request =  System.Net.WebRequest.Create(@"https://yesno.wtf/api");
request.Timeout = 1000;
request.Method = "GET";
try
{  
  using (var response = request.GetResponse())
   {
      using (var stream = response.GetResponseStream())
      {
        var reader = new StreamReader(stream, System.Text.Encoding.UTF8);
        Print(reader.ReadToEnd());
      }
   }
 }
 catch (System.Net.WebException e)
 {
    Print(e.Message);
 }

RestApiExample.gh (5.9 KB)

This example doesn’t need an api key. In your case, I suppose that would go in the headers:

request.Headers.Add("x-api-key", "your api key");
You might also want to add the content type:
request.ContentType = "application/json";

Finally, to parse the response, I’d recommend using Json.net and creating a class that matches the properties of the response. Something like:

public class OpenSensorMessage
  {
    public int date {get; set;}
    public int rssi {get; set;}
    public bool lowBattery {get; set;}
    public bool heartbeat {get; set;}
    public int lsnr {get; set;}
    public string id {get; set;}
    public string type {get; set;}
    public string deviceId {get; set;}
    public List<string> tags {get; set;}
  }
1 Like
Call REST api from ghPython
(P D Siedler) #5

Oh wow, this is great, thanks a lot! I’ll let you know how things go!

(P D Siedler) #6

I put everything together as you told me to. I get the error: The remote server returned an error: (502) Bad Gateway. Is that a problem of the code or the actual server?

(Luis Fraguada) #7

Hmm, not sure. I went ahead and signed up for an account an an api key. I am using this documentation: https://api.opensensors.io/index.html Is that correct? I picked out one kind of request, the code is very similar, but the API Key needs to be entered. It looks like this:

var request = System.Net.WebRequest.Create(@"https://api.opensensors.io/v1/messages/user/fraguada");
request.Timeout = 1000;
request.Method = "GET";
request.Headers.Add("Authorization", "api-key YOURAPIKEYHERE");
request.ContentType = "application/json";
try
{
  using (var response = request.GetResponse())
  {
    using (var stream = response.GetResponseStream())
    {
      var reader = new StreamReader(stream, System.Text.Encoding.UTF8);
      Print(reader.ReadToEnd());
    }
  }
}
catch (System.Net.WebException e)
{
  Print(e.Message);
}

Since I don’t have any messages, I get

{"messages":[]}

With the example you posted, I’m not sure what the projectURI parameter is meant to be (I’m not familiar with the nomenclature used on OpenSensors.io).

1 Like
(Luis Fraguada) #8

FYI I was able to post some messages like this:

var request = (System.Net.HttpWebRequest) System.Net.WebRequest.Create("https://realtime.opensensors.io/v1/topics//users/fraguada/hei?client-id=YOURDEVICECLIENTID&password=YOURDEVICEPASSWORD");
request.Timeout = 1000;
request.Method = "POST";
request.Headers.Add("Authorization", "api-key YOURAPIKEY");
request.ContentType = "application/json";
request.Accept = "application/json";

using(var streamWriter = new StreamWriter(request.GetRequestStream()))
{
  string json = "{\"data\": \"My Third Msg\"}";
  streamWriter.Write(json);
  streamWriter.Flush();
  streamWriter.Close();
}

try
{
  var httpResponse = (System.Net.HttpWebResponse) request.GetResponse();
  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  {
    var result = streamReader.ReadToEnd();
    Print(result);
  }
}
catch (System.Net.WebException e)
{
  Print(e.Message);
}
1 Like
(P D Siedler) #9

Thanks a lot!
in the “api-key YOURAPIKEYHERE” you only exchanged YOURAPIKEYHERE with the actual api-key, right? So it would look like this “api-key 4823Werwe9reWErWE499” ? And for “fraguada” I just place my own user-name I used to log in, right? “https://api.opensensors.io/v1/messages/user/fraguada

Best, Phil

(Luis Fraguada) #10

As I understand it, you need to create your topic. In my case, I created a topic (horribly named) “hei”. The ‘path’ to the topic is: /users/fraguada/hei, so conceivably, your topic would be something like /users/YOURUSERNAME/YOURTOPICNAME.

Correct.

Correct, though I wouldn’t share your api key in a public forum :wink: .

1 Like
(P D Siedler) #11

Thank you!!
It’s a fake key, just to showcase :slight_smile:
How did you create a topic? (I probably should know that)

(P D Siedler) #12

Also I just got informed that this is the old api (https://api.opensensors.io/index.html) and that I need to use the new one: https://apidocs.opensensors.com/

(Luis Fraguada) #13

I logged into here: https://publisher.opensensors.io and created a topic by navigating to the topic section:

1 Like
(Luis Fraguada) #14

Ok. Yeah, not sure. That is a gall to get messages as a GET, not a POST (to add data to the topic), and I only see one:

1 Like
(P D Siedler) #15

So essentially I need to add parameters to my GET request as stated in https://apidocs.opensensors.com/, do you know how to implement that into the component?

(Luis Fraguada) #16

My first example was a GET: C# call REST client with x-api-key within grasshopper

Can you log into opensensors.com? I only seem to be able to register and log into opensensors.io. If I click the authorize button on the swagger page, I don’t have any available authorizations.

1 Like
(P D Siedler) #17

Hi Luis,
I figured it out for now, have a look:

var request = System.Net.WebRequest.Create(@"https://api.opensensors.com/getProjectMessages?fromDate=2017-12-02&toDate=2017-12-03&projectUri=my-project");

request.Timeout = 1000;
request.Method = "GET";
request.Headers.Add("X-Api-key", "fakeapikey");
request.ContentType = "application/json";

try
{
  using (var response = request.GetResponse())
  {
    using (var stream = response.GetResponseStream())
    {
      var reader = new StreamReader(stream, System.Text.Encoding.UTF8);
      Print(reader.ReadToEnd());
    }
  }
}
catch (System.Net.WebException e)
{
  Print(e.Message);
}

Now can you maybe help me out with one last thing? Is there a way I can implement my parameters in a cleaner way? Maybe so I can even use them as inputs for the grasshopper components instead of manually writing them into the URL like I did here: @“https://api.opensensors.com/getProjectMessages?fromDate=2017-12-02&toDate=2017-12-03&projectUri=my-project” ?

Thanks so much!

(P D Siedler) #18

I guess i figured it out. Things are getting beautiful from now on :wink:
Thanks again for your kind help!

1 Like
(Golavillimohan) #19

I want to GET all_details of Employee from API provided by third party [ authentications ], and the details provided me for access the data are UserName ,Password ,API key ,Resource ,Parameters

Resource (GET employees/ ) && Parameters (• all_details (boolean) - For large queries, data is limited to important information. By passing this argument the api will return all data for each record. • limit (integer) - Limits the number of records returned. • offset (integer) - Offsets the start of the collection by the given number of records. )

I tried to execute this code but i am getting 401 error, I am new to this service please help me.

Here is the code
string url = “https://api.midenity.com/api/v1.1/advertiser/”;
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url);
GETRequest.Method = “GET”;
GETRequest.Headers.Add(“api-key”, “apikeyhere”);

        textBox1.Text = "Sending GET Request";
        HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
        Stream GETResponseStream = GETResponse.GetResponseStream();
        StreamReader sr = new StreamReader(GETResponseStream);

        textBox1.Text = "Response from Server" + sr.ReadToEnd();

I try to run this code but i am facing 401 error, I am new to this service please help me

#20

Speaking of API keys – is there a best practice for using API keys within a GHA assembly that protects them from being peeped using ILSpy or other decompiler options?