How to get data from API request? - c#

I'm pretty new to C# and this is my first time getting data from an api. I was wondering how do I get or call the data collected in this api request (MakeRequest). Preferably assign the data to a public string. The data from the api request is in json format.
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
public partial class Form1 : Form
{
public async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request parameters
queryString["seasonId"] = "{string}";
var uri = "https://www.haloapi.com/stats/{title}/servicerecords/arena?players={players}&" + queryString;
var response = await client.GetAsync(uri);
}
}
}

So if the call succeeded, you should have your JSON string returned in the response variable you assign in the last line.
Use your debugger and inspect that variable. If you look at the MSDN doc for your GetAsync() method (Link), you can easily find out that the variable is of the type HttpResponseMessage. This class has an own page here telling you that there's a property Content.
This is your JSON string, now might come the part where you have to do some deserializing. Have fun.

Related

Make my own API capable of requesting from another API

I have an existing and functioning API, which now have to be able to get data from another external API. How do i do that best?
I have tried with using HTTPClient, but i can't seem to get it to work. The error i get:
"No MediaTypeFormatter is available to read an object of type 'IList`1' from content with media type 'text/html'." -> I get this error on line 37. Can you spot it and/or tell me how I can do this differently, taking into account that all i want is the data (From the external API) and not to display it using a view, as this is an API?
Code below. I have also created a Pastebin: https://pastebin.com/MuKjEVys
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
namespace API.Controllers
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ExternalApiController : Controller
{
private string ExternalApiLink = "https://blablabla.com/api";
private string ExternalApiLinkGet = "/module/1/";
[HttpGet("getdata")]
public ActionResult<ExternalApi> GetDataFromExternal()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ExternalApiLink);
var requestApi = client.GetAsync(ExternalApiLinkGet);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "XXXX");
requestApi.Wait();
var resultFromApi = requestApi.Result;
if (resultFromApi.IsSuccessStatusCode)
{
var readResponse = resultFromApi.Content.ReadAsAsync<IList<ExternalApi>>();
readResponse.Wait();
var data = readResponse.Result;
return Json(data);
}else
{
return NotFound();
}
}
}
}
}
Your response content seems to be json, while the content-type is text/html. If that is the case, the first thing to do would be to call the party that is exposing the service and have them fix it. In the meantime you could just read the content of the response as a string, and deserialize that string:
// Note that I made this method async.
public async Task<IActionResult> GetDataFromExternal()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ExternalApiLink);
// note that I moved this line above the GetAsync method.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "XXXX");
// note that I'm disposing the response
using (var response = await client.GetAsync(ExternalApiLinkGet))
{
if (response.IsSuccessStatusCode)
{
// Since the response content is json, but the content-type
// is text/html, simply read the content as a string.
string content = await response.ReadAsStringAsync();
// You can return the actual received content like below,
// or you may deserialize the content before returning to make
// sure it is correct, using JsonConvert.DeserializeObject<List<ExternalApi>>()
// var data = JsonConvert.DeserializeObject<List<ExternalApi>>(content);
// return Json(data);
return Content(content, "application/json");
}
else
{
return NotFound();
}
}
}
}

Microsoft Linguistic Analysis API example HttpUtility does not exist

I'm trying to check Microsoft Linguistic Analysis API, basic example, so I have subscribed and addad my Key 1 in Ocp-Apim-Subscription-Key and Key 2 into the subscription key here client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");.
Then I add Newtonsoft.Json with Manage NuGet Packages into the References of Application, even it is not listed in using of particular example using Newtonsoft.Json; using bNewtonsoft.Json.Serialization; not sure, I'm new with this tool.
I'm trying to check this example Linguistics API for C# to get some natural language processing results for text analysis mainly of Verb and Noun values according to this example results So I'm not sure if I'm on the right direction with this example, or possible I've missed something to install, maybe I need some additions. I found this Analyze Method not sure how and if I have to use it for this particular goal.
But seems like something is wrong with var queryString = HttpUtility.ParseQueryString(string.Empty); and HttpUtility does not exist.
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
static class Program
{
static void Main()
{
MakeRequest();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
var uri = "https://westus.api.cognitive.microsoft.com/linguistics/v1.0/analyze?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{body}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
response = await client.PostAsync(uri, content);
}
}
}
}
You can create a new writeable instance of HttpValueCollection by calling System.Web.HttpUtility.ParseQueryString(string.Empty), and then use it as any NameValueCollection, like this:
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
Try adding a reference to System.Web, and possibly to System.Runtime.Serialization.

How to get an http json response from the philips hue bridge after a put

I'm trying to get a json response back from the Philips hue after I complete a PUT request. The Philips hue has a build in web server command line, when I send a basic json message like "{"on":True}" using the hue web interface I get a json response back telling me that the request was a success. The message looks like this:
"[
{
"success": {
"/lights/1/state/on": true
}
}
]"
Right now when I send a command to the hue via my setup below, I always get a TRUE .IsSuccessStatusCode (I'm assuming becasue the message was recieved by the hue?) even if I send some json that should cause an error. Example; I could use the json {"on":Cause an error} and still get a TRUE.
So I'm trying to figure out how to get the above json response back from the hue after I've sent a PUT. Below is the code I'm using.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
async static void setLight()
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
String myJson = "{\"on\":false}";
var content = new StringContent(myJson, Encoding.UTF8, "application/json");
HttpResponseMessage returnStatement = await client.PutAsync("http://192.168.1.3/api/139f12ce32a30c473368dbe25f6586b/lights/1/state", content);
Console.WriteLine(returnStatement.IsSuccessStatusCode);
}
Console.WriteLine("Return Statment:" + await returnStatement.Content.ReadAsStringAsync());
This returns the json hue response I was looking for. I just kept getting basic http info back until I put the await keyword in front of it. Shout out to Q42.hueApi, I took a peak at your code and that helped greatly.

'HttpWebRequest' does not contain a definition for 'GetResponseAsync'

I am new in xamarin and visual studio,I have followed this tuto from microsoft:
enter link description here
to create a cross platform application,but I get this error:
'HttpWebRequest' does not contain a definition for 'GetResponseAsync' and no extension method 'GetResponseAsync' accepting a first argument of type 'HttpWebRequest' was found (a using directive or an assembly reference is it missing * ?)
and this is my code in which I get this error:DataService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace shared
{
//This code shows one way to process JSON data from a service
public class DataService
{
public static async Task<dynamic> getDataFromService(string queryString)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryString);
var response = await request.GetResponseAsync().ConfigureAwait(false);
var stream = response.GetResponseStream();
var streamReader = new StreamReader(stream);
string responseText = streamReader.ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
}
Please how can I solve it, I checked the HttpWebRequest documentation but I didn't get well the problem
thanks for help
Not sure about HttpWebRequest - but a newer and now recommended way to get data is the following:
public static async Task<dynamic> getDataFromService(string queryString)
{
using (var client = new HttpClient())
{
var responseText = await client.GetStringAsync(queryString);
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
Try that and let me know if it works.

How do I access the content of an API response?

I've tried implementing the simplest case of this with a call to Mandrill's API using the method "ping." The response should be pong. Using a valid key, the response seems to work. However, I am having trouble accessing the content of the response.
The code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MandrillAPI
{
class Program
{
static void Main(string[] args)
{
string ping = "https://mandrillapp.com/api/1.0/users/ping.json";
string key = "?key=123";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ping);
HttpResponseMessage response = client.GetAsync(key).Result;
Console.WriteLine(response.ToString());
Console.Read();
}
}
}
How do I unpack the response from the call? Ultimately, I need to harvest emails from the server using the API, so I'll need to somehow preserve the structure of the json objects so I can access the details of the email.
If you just want to read the response as a string:
string content = response.Content.ReadAsStringAsync().Result
If you want to deserialize to some class (in this case the type MyClass):
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result)
I would use something like JSON.Net to serialize it to a C# object that you can then use.

Categories

Resources