IGDB V3 Request - c#

Does anyone know how to properly search for games using the Internet Game Database API as of version 3? I'm trying to use IGDB to do a simple game search. For each game that matches the search terms, I'd like to retrieve the game's name, genres, developers and publishers, it's initial release date, and the URL of the cover. Through some Googling I'd gotten it working through the old URL parameters, but something seems to have changed on their end, and those no longer work. The version 3 documentation says to use Apicalypse to send the fields you want back in the body of the web request, but I can't for the life of me figure out how to do that. I'm using AJAX to send the search terms to the controller, and sending the results back via a JSON object. I'm getting a 400 Bad Request error every time, no matter the syntax I use for the fields. The documentation says that using URL parameters should still work, but they do not. Here's my controller code.
[HttpPost]
[WebMethod]
public JsonResult LookUpGames(string search)
{
string url = "https://api-v3.igdb.com/games/?search=" + search
+ "&fields=name,genres,involved_companies,first_release_date,cover";
HttpWebRequest gameRequest = (HttpWebRequest)WebRequest.Create(url);
gameRequest.Accept = "application/json";
gameRequest.Headers.Add("user-key", "[MYUSERKEY]");
WebResponse gameResponse = (HttpWebResponse)gameRequest.GetResponse();
string responseString = new StreamReader(gameResponse.GetResponseStream()).ReadToEnd();
return Json(new { result = responseString });
}
UPDATE: Thanks for the pointer, Jake. I'm now hitting the servers with the following code.
HttpResponse<JsonResult> jsonResponse = Unirest.post("https://api-v3.igdb.com/games")
.header("user-key", "[MYUSERKEY]")
.header("Accept", "application/json")
.body("fields name,genres,platforms,involved_companies,cover").asJson<JsonResult>();
JsonResult jsonResult = Json(new { result = jsonResponse });
return jsonResult;
There is no JsonNode in C# apparently, so I tried JsonResult, and the .asJson() seems to be .asJson(). I just fiddled with it until it worked. But I'm still not getting back a list. I'm getting a 400 Bad Request error. So even in this new format, it's still not liking the fields I'm giving it. According to the structure in the documentation, the fields I'm giving it are in fact there in the Game endpoint. So I don't know what could be wrong. Any other ideas anyone?

I decided to try the query approach again, and somehow it now works. Here's my controller method that works. Not sure which tweaks made it work again, but it does.
[HttpPost]
[WebMethod]
public JsonResult LookUpGames(string search)
{
string url = "https://api-v3.igdb.com/games?search=" + search +
"&fields=name,genres.name,platforms.name,involved_companies.*, involved_companies.company.*,first_release_date,cover.url";
HttpWebRequest gameRequest = (HttpWebRequest)WebRequest.Create(url);
gameRequest.Accept = "application/json";
gameRequest.Headers.Add("user-key", "[MYUSERKEY]");
WebResponse gameResponse = gameRequest.GetResponse();
StreamReader sr = new StreamReader(gameResponse.GetResponseStream());
string responseString = sr.ReadToEnd();
sr.Close();
JsonResult jsonResult = Json(new { result = responseString });
return jsonResult;
}

Related

Restsharp: An error occurred while sending the request, The response ended prematurely

I know that stack overflow is full of problems like this but i have not found answer in the other ones, also, my problem is really weird.
We have an integration with a variety of WooComerce/Wordpress shops.
I have an only function for every task that i do in all the pages and it is later called whit the data of the differents markets, for example, this is the method to get all the orders "Is a simple GET request using RestSharp":
public static async Task<List<string>> GetOrdersWooComerce(string urlinicio, string secreto, string cliente)
{
var url = urlinicio+"/wp-json/wc/v3/orders?consumer_key="+cliente+"&consumer_secret="+secreto+"&status=processing";
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
JArray jsongo = JArray.Parse(response.Content);
List<string> keys = new List<string>();
foreach (var j in jsongo.AsJEnumerable())
{
keys.Add(j["id"] + "");
}
return keys;
}
It works perfectly with all the shops except one that returns me an empty content with the next exception:
I only am using an url that returns a json, i dont know where is the error in that simple request... also if i copy the url and paste it in postman it works.
¡Even in the google search it returns me the json! Is as simple as that, only an url, but in my code doesn't work only with that shop :(

Instagram explore/tags API doesn't return JSON data

The last few days, Instagram hashtag query string "explore/tags/hashtag_Name/?__a=1" started to not return "JSON" data.
For example when I send web request at the beginning two or three times I get JSON data but then for other requests I always get some html file code with title login-Instagram. I don't know if there are some changes with Instagram API some limitation for requests.
Anyone who has same problem who can help me?
So here is my code:
public Task<T> GetInstaHashtags(string search_Hashtag){
WebRequest instaHashtag = WebRequest.Create("https://www.instagram.com/explore/tags/"+ search_Hashtag + "/?__a=1";
instaHashtag.Method = "GET";
instaHashtag.Headers[HttpRequestHeader.ContentType]="application/json";
string response = null;
using(var getResponse = instaHashtag.GetResponse().GetResponseStream()){
var headerResponse = new StreamReader(getResponse);
response = headerResponse.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<T>(response);
return result;
}

learning .net core 3.1 - very first attempt at consuming API webservice

I'm brand new to .net core 3.1 - not a lot of oop experience period - I have 20 years software development experience using procedural languages on IBMi. Been working through a tutorial to consume an API that I have created on my IBMi... I'm stuck...
Below is my HomeController... What I'm able to do by running this code thus far...
1.) connects to my IBMi endpoint
2.) it does invoke the correct backend API pgm
3.) backend API pgm does indeed take json string from URI and process it like it should, and produces a json string response.
issues..
1.) ultimately i'd like to pass this json request string in the body and not the URI
2.) while everything is working with passing the json string in the URI, when the json string response is sent back, there is an issue processing that response. My guess is that it is expecting a json object back and not a string.
The error is...
JsonException: The JSON value could not be converted to
System.Collections.Generic.IEnumerable`1[coreiWS.Models.ProductKey].
Path: $ | LineNumber: 0 | BytePositionInLine: 1.
the generated json string response is... (or could also contain a trial key value - nonetheless, both are valid json in string format)...
{
"success": 0,
"resultMessage": "Error RST00001R - Invalid - Product Code Already Granted 2 Trial Keys. Please Email Us At xxxxxxxxxx#gmail.com To
Discuss Your Future Business Requirements Utilizing CoreiRST." }
and the code causing it is...
var responseStream = await response.Content.ReadAsStreamAsync();
productKeys = await JsonSerializer.DeserializeAsync
<IEnumerable<ProductKey>>(responseStream);
I would be extremely grateful for anyone that could help guide me in the right direction with getting this working.
the complete HomeController Code is...
public class HomeController : Controller
{
// jhv - add this...
private readonly IHttpClientFactory _clientFactory;
public IEnumerable<ProductKey> productKeys { get; set; }
public HomeController(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
// jhv - add this...
public async Task<IActionResult> Index()
{
//var user = Authenticate().Result;
//if (user == null)
//return View();
var request = new HttpRequestMessage(HttpMethod.Get,
"http://xxxxxxxxxxxxxxxxxxxxxxxxx/{\"env\":\"xxx\",\"command\":\"getTrialKey\",\"payload\":{\"productCode\":\"MFT 102A08R EPCA 00007\"}}");
//request.Headers.Add("Authorization", "Bearer " + user.Token);
request.Headers.Add("Authorization", "Basic xxxxxxxxxxxxxxxxxx");
//request.Headers.Add("text/plain", "{\"env\":\"xxx\",\"command\":\"getTrialKey\",\"payload\":{\"productCode\":\"MFT 102A08R EPCA 00007\"}} \r\n");
var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("text/plain"));
var response = await client.SendAsync(request);
if(response.IsSuccessStatusCode)
{
var responseStream = await response.Content.ReadAsStreamAsync();
productKeys = await JsonSerializer.DeserializeAsync
<IEnumerable<ProductKey>>(responseStream);
}
else
{
productKeys = new List<ProductKey>();
}
return View(productKeys);
It looks like your JSON is returning a singular object, but you are trying to map it to an IEnumerable<ProductKey>.
That might get you through the first error message.

How can I parse information returned from the Twitter Search API?

I am currently building a web application that interacts with the Twitter Search API and returns tweets based on input. I am getting data returned to me, but it is coming in such a way that I do not know what to do with it. Can somebody suggest an improvement or how I can handle this data so I can format the results?
Here is the code:
public ActionResult SearchTwitter(string authenticationCode, TwitterSearch twitterSearch) //TwitterSearch holds information needed to build the URL
{
string url = BuildURL(twitterSearch);
var gettimeline = WebRequest.Create(url) as HttpWebRequest;
gettimeline.Method = "GET";
gettimeline.ContentType = "application/x-www-form-urlencoded";
gettimeline.Headers[HttpRequestHeader.Authorization] = "Bearer " + authenticationCode;
JsonResult result = new JsonResult();
try
{
var respbody = ""; //used to be string
using (var resp = gettimeline.GetResponse().GetResponseStream())//there request sends
{
var respR = new StreamReader(resp);
respbody = respR.ReadToEnd();
}
result = Json(respbody);
}
This is the trouble spot, everything else is fine (such as the catch and return statement at the end).
I am not sure where to go to effectively parse this data, as the JsonResult.Data object is a string, which isn't helpful in this situation.
Let me know if you need any more clarification.
You can use Json.net, like this:
var respbody = ""; //used to be string
using (var resp = gettimeline.GetResponse().GetResponseStream())//there request sends
{
var respR = new StreamReader(resp);
respbody = respR.ReadToEnd();
JObject timeline = JObject.Parse(respbody);
// use the docs at Newtonsoft.com to figure out how to read timeline
}
Notice that I added JObject.Parse(respbody), which gives you a JObject containing the parsed JSON data. The documentation at Newtonsoft.com is pretty decent and shouldn't take much time to work through to figure out the rest.
You can install the Newtonsoft.Json package from NuGet. Alternatively, you might also consider a 3rd party library, like LINQ to Twitter (which I wrote), to make this even easier.

What is the return type to redirect to an external page in ASP.NET MVC?

This is mostly linked to my earlier question but is different than that.
I am integrating a payment gateway in my code and I have got a post URL to post to.
So on click of a button the control goes to the controller from my view where I am calling a method to do the post.
So my concern is I am currently using the below code for posting to the URL however the provider is not ready so I am not able to test but I want to know if I am using the correct return type here.
Will this redirect me to the provider website/page from the controller?
What is the correct way of doing it?Some where I ready I can only do it from Javascript and not from controller.
Can body please clarify I have been struggling with this for the past few days?
public HttpWebResponse SendPostRequest(string data, string url)
{
var datetime = DateTime.UtcNow;
data = string.Format("ID*1100|Field01*19101|FirstName*james|LastName*MEZE|AmountDue*20000|CurrentTime*7/5/2016 4:25 PM);
var requestPayload = Encrypt(data);
url = "https://www.example.com/Account/SSO/Home";
HttpWebRequest httpRequest = (HttpWebRequest) HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "text/plain";// "application/x-www-form-urlencoded";
httpRequest.ContentLength = encryptedRequestPayload.Length;
var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(encryptedRequestPayload);
streamWriter.Close();
/*var response = (HttpWebResponse)httpRequest.GetResponse();
var statusCode = response.StatusCode;
var description = response.StatusDescription;
var sr = new StreamReader(response.GetResponseStream());
var text = sr.ReadToEnd();*/
return (HttpWebResponse) httpRequest.GetResponse();
}
Returning the HttpWebResponse is only showing me a blank page with the line System.Net.HttpWebResponse.
But in the response I am seeing the XML message with the response saying the service is down contact adminstrators.
Why am I not able to see that message in the web page? please help.
To redirect to an external web page you can use the Redirect method and pass the url.
public ActionResult SendPostRequest(string data, string url)
{
//do youre stuff
return Redirect("https://www.example.com/Account/SSO/Home");
}
That will only work for HTTP GET calls because the browser do a new GET when they become a redirects result.
If you want to POST to another page and show the result page to your visitor, I think the only possible way to achieve this is using JavaScript. For this you can return some simple html with a <script> tag which sends a <form> with HTTP POST.
//$ is the C#6 syntax of string.Format
return Content($#"
<form action='https://www.example.com/Account/SSO/Home' id='myForm' method='post'>
<input type='hidden' name='value1' value='{value1}' />
<input type='hidden' name='value2' value='{value2}' />
</form>
<script>
document.getElementById('myForm').submit(); //submit the form
</script>");
I got the idea with a form from this answer
You seem to have 2 problems:
1) The server is not responding the way you want. You probably will have to contact the admin as the message says.
2) You are not returning something the ASP.NET MVC is expecting so the ToString() method called by the framework will only display System.Net.HttpWebResponse.
You are close to it though. Shouldn't you be returning the text you get from the response stream?
You can do so by writing:
return Content(text); // after uncommenting your code.
This answer will show you a successful attempt at posting data to a server and passing the response to the client.

Categories