C# example to authorise and get data from API

Hello,

I’m a real newbie to requesting API data from here and using HTTP requests in General. I have an account with a application and key so far.

However, does anyone have a complete sample application written in C# to make a GET request and return the results.

Currently, I have some code written, but I’m getting a Authorisation error (407). Obviously, I need to set up and get my credentials working send the get request and return the results. I’m using the HttpWebRequest object. Can anyone help with this or have an sample code or tutorials on how to do this?

Actually, the error message is as follows.

“The remote server returned an error: (407) Proxy Authentication Required.”

Could this be to do with our proxy server? If so, can someone explain what is going on here and how I can overcome this?

Here is my code:

    static void GetCompanyFromNumber()
    {

        string credentials = String.Format("{0}:{1}", "API_KEY", "XLO5bXXXXXX3Js86dDqkXuoXXXXXXP9CcWLnB33tN");
                                       // Not my real API KEY....
        byte[] bytes = Encoding.ASCII.GetBytes(credentials);
        string base64 = Convert.ToBase64String(bytes);
        string authorization = String.Concat("Basic ", base64);
       
        try
        {
            // create my web request
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("https://api.companieshouse.gov.uk/company/08261946");
            // use default credentials
            webReq.UseDefaultCredentials = true; webReq.Headers.Add("Authorization", authorization);
            // sets the method as a get
            webReq.Method = "GET";
            // performs the request and gets the response
            HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
            // prints out the status code
            Console.WriteLine(webResp.StatusCode);
            // prints out the server
            Console.WriteLine(webResp.Server);

            // create a stream to the response
            Stream answer = webResp.GetResponseStream();
            // read the stream
            StreamReader _answer = new StreamReader(answer);
            // display the stream
            Console.WriteLine(_answer.ReadToEnd());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

Thanks in advance,

R.

You need to add a colon after your key in the in the authorization header (essentially making it key:password but there isn’t a password)

The authorization documents elude to this but don’t actually state it explicitly for some reason.

Hi Ash,

Many thanks for your response. I have tried to add the colon in 3 places without success I still get the same (407) error message.

Try 1:
string credentials = String.Format("{0}:{1}", “API_KEY”, “XLO5bXXXXXX3Js86dDqkXuoXXXXXXP9CcWLnB33tN:”);
// Not my real API KEY…
Try 2:
webReq.UseDefaultCredentials = true; webReq.Headers.Add(“Authorization”, authorization + “:”);
// sets the method as a get

Without success. Can you provide an example of where I should put the colon?

Thanks in advance,

R.

I don’t know if this will cure you 407 error, which I’m sure is caused by your proxy (but it may be turning the 401 into a 407… at a guess!), but you’re not creating the basic auth string correctly.

If I’m reading your code correctly (and my rusty C#) Iyou should have:

string credentials = String.Format("{0}:{1}", "XLO5bXXXXXX3Js86dDqkXuoXXXXXXP9CcWLnB33tN", "");

The actual authentication header becomes: base64 (“username:password”) where username is your API_KEY, password is blank.

Hello All,

I’ve managed to make a successful request from Companies House and therefore thought I would share the code. Thanks to all that replied to this!

The (407) error I encountered was definitely to do with the Proxy Server. When I tried to access the site from home it worked fine!

This version definitely works but need to parse the returning data. After doing some research I believe that webClient is a better way of consuming Rest data.

However if anyone has any suggestions how I can parse or deserialize this data I would be grateful?

    static void GetCompanyFromNumber()
    {
        string credentials = String.Format("{0}:{1}", "XXXXXXF-3Js86dDqkXuoiLx2R0P9XXXXXXXX", "");
        // Not my real key!!!!
        byte[] bytes = Encoding.ASCII.GetBytes(credentials);
        string base64 = Convert.ToBase64String(bytes);
        string authorization = String.Concat("Basic ", base64);

        try
        {
            // creates a web request
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("https://api.companieshouse.gov.uk/company/{your_company_number_goes_here}");

            // use default credentials
            webReq.UseDefaultCredentials = true; webReq.Headers.Add("Authorization", authorization);

            // sets the method as a get
            webReq.Method = "GET";

            // performs the request and gets the response
            HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();

            // prints out the status code
            Console.WriteLine(webResp.StatusCode);

            // prints out the server
            Console.WriteLine(webResp.Server);

            // create a stream to the response
            Stream answer = webResp.GetResponseStream();

            // read the stream
            StreamReader _answer = new StreamReader(answer);

            // display the stream
            Console.WriteLine(_answer.ReadToEnd());
        }
        catch (Exception ex)
        {
            // The remote server returned an error: (407) Proxy Authentication Required.
            Console.WriteLine(ex.Message);
        }
    }

Thanks in advance,

R.

Hi Richard,

I recently did some work similar to your own and I get the data I want out of the request by doing the following:

        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        if (webResponse.StatusCode != HttpStatusCode.OK) Console.WriteLine("{0}", webResponse.Headers);
        using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
        {
           //response as a string
            string s = reader.ReadToEnd();
           //conversion to data object 
            var companyData = Json.Decode(s);
            reader.Close();
        }

This way we have the whole thing as a dynamic object which is far easier to deal with in my system.

Access the data by using (I want the accounting data hence the example):

var accountsDue = DateTime.ParseExact(companyData.accounts.next_due as string, “yyyy-MM-dd”, null, DateTimeStyles.None);

Now the data you want is a variable you can do whatever you want with it - I myself pass it into a class and then on into the DB if the data held against that company is out of date.

Hope this helps - can provide the full request code if necessary

N.B: I’m not certain the API returns JSON by default, if not set it on the request with
> webRequest.ContentType = “application/json”;

and the above should work

Yours,

James

Hi, I appreciate that this is an old thread, but would you be able to provide the full request code? Thanks!