C# eBay Listing Recommendation API - c#

I'm having trouble getting any type of response from the Listing Recommendation API. I keep getting a generic 500 message on my return. I've set up my headers the way they recommend here: https://developer.ebay.com/devzone/listing-recommendation/Concepts/MakingACall.html
I've tried using the information from the documentation on the call here: https://developer.ebay.com/devzone/listing-recommendation/CallRef/itemRecommendations.html#Samples
But every variation of my code comes up bad. Below is a sample of the code. I've tried it with and without the commented out line of code with the same results. It always fails on the line response.GetResponseStream. Thanks for your help.
public static void test(string AuthToken, string listing, log4net.ILog log)
{
string url = "https://svcs.ebay.com/services/selling/listingrecommendation/v1/item/" + listing + "/itemRecommendations/?recommendationType=ItemSpecifics";
var listingRecommendationRequest = (HttpWebRequest)WebRequest.Create(url);
listingRecommendationRequest.Headers.Add("Authorization", "TOKEN " + AuthToken);
listingRecommendationRequest.ContentType = "application/json";
listingRecommendationRequest.Accept = "application/json";
listingRecommendationRequest.Headers.Add("X-EBAY-GLOBAL-ID", "EBAY-US");
listingRecommendationRequest.Method = "GET";
//listingRecommendationRequest.Headers.Add("recommendationType", "ItemSpecifics");
var response = (HttpWebResponse)listingRecommendationRequest.GetResponse();
string result;
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
var reader = new JsonTextReader(new StringReader(result));
while (reader.Read())
{
if (reader.Value != null)
{
// Read Json values here
var pt = reader.Path;
var val = reader.Value.ToString();
}
}
}
Edit: Adding image of what I'm trying to accomplish. I'm trying to get the item specifics recommendations that are suggested by eBay when manually editing a listing. These suggestions change based on what is in your title.

Related

Mapping JSON from Yahoo! Finance API to C# objects [duplicate]

This question already has answers here:
Deserialize JSON data with C#
(4 answers)
Closed 1 year ago.
I am a student working on a project. I am trying to use the Yahoo! Finance API as a source for my data https://www.yahoofinanceapi.com . I can use HttpWebRequests to call the API and get the "OK" code, see the code below on how I did it:
string BaseURL = "https://yfapi.net/v6/finance/quote?symbols=AAPL";
string addSymbol = "%2C";
string URL = BaseURL;
foreach (string stock in stocks)
{
URL += addSymbol + stock;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Headers.Add("X-API-KEY", "[My API key]");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.ContentType);
Console.WriteLine(response.StatusCode);
response.ContentType gives back "application/json".
response.StatusCode gives back "OK".
Since the response is a JSON I tried to parse it into a string using .ToString() but this obviously doesn't work. When I print it, it just says "System.Net.HttpWebResponse" instead of the showing the actual data in the JSON.
After that I tried to deserialize it using newtonsoft
Results result = JsonConvert.DeserializeObject<Results>(request.GetResponse().ToString());
where Results is a class I made where there is a list of stocks, Stock is also a class I made with some variables in it with the same names of variables in the JSON response.
I got a JSON response from PostMan when I tested the API, opened the response to see what kind of data it contained.
When I ran my code I got the following error message:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: S. Path '', line 0, position 0.'
This was as far as I got, I tested a few other methods trying to get this working but this one worked the "best".
My biggest issue at the moment is mapping the response into a c# object.
Anything that can help me understand is appreciated :D
You're trying to serialise the HttpWebResponse object into Results, which means deserialisation won't work.
The data is still wrapped & won't be in the format of the Results object.
The GetResponseStream() method can be used to get the contents of the HTTP response as a stream, which can then be deserialised directly, in this case, using Json.NET.
Replace this section:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.ContentType);
Console.WriteLine(response.StatusCode);
With this:
var serializer = new JsonSerializer();
using (var response = (HttpWebResponse)request.GetResponse())
{
var encoding = Encoding.GetEncoding(response.CharacterSet);
using var responseStream = response.GetResponseStream();
using var reader = new StreamReader(responseStream, encoding);
using (var jsonTextReader = new JsonTextReader(reader))
{
Console.WriteLine(response.ContentType);
Console.WriteLine(response.StatusCode);
Results result = serializer.Deserialize<Results>(jsonTextReader);
}
}
Alternatively, a much better solution if you're using .NET 4.5 <= would be to use HttpClient like below:
private static readonly HttpClient httpClient = new HttpClient();
...
string BaseURL = "https://yfapi.net/v6/finance/quote?symbols=AAPL";
string addSymbol = "%2C";
string URL = BaseURL;
foreach(string stock in stocks) {
URL += addSymbol + stock;
}
client.DefaultRequestHeaders.Add("X-API-KEY", "[My API key]");
var data = await httpClient.GetStringAsync(address);
Results result = JsonConvert.DeserializeObject<Results>(data);

C# WebRequest 400 Error when trying GET orderBy with firebase, works fine without orderby

So, I am trying to get a list of objects from the firebase online database with the help of a WebRequest, whcih works fine, but when I try to query it with orderyBy="Price"&startAt=2 then the request gives me a 400 error and I can't understand why. Here is the code
private static string url = "https://project-name.firebaseio.com/Services.json?orderBy=\"Price\"&startAt=2";
public static async Task<List<Service>> GetServices()
{
List<Service> services = new List<Service>();
JObject j;
var request = WebRequest.CreateHttp(url.ToString());
request.Method = "GET";
request.ContentType = "application/json";
using (var response = await request.GetResponseAsync())
{
var json = (new StreamReader(response.GetResponseStream()).ReadToEnd());
dynamic deserialized = JsonConvert.DeserializeObject(json);
j = (Newtonsoft.Json.Linq.JObject)(deserialized);
try
{
foreach (System.Collections.Generic.KeyValuePair<string, Newtonsoft.Json.Linq.JToken> obj in j)
{
Service s = JsonConvert.DeserializeObject<Service>(obj.Value.ToString());
services.Add(s);
}
return services;
}
catch (NullReferenceException exception)
{
return new List<Service>();
}
}
}
Please help!
I have managed to fix this bug, apparently what I was supposed to do was edit the rules of the Firebase Realtime Databse to have the index.On property. For anybody who's getting this error, please look out

Connecting to Tagpacker.com from C# with a HttpWebRequest

Does anyone know how I can post to the tagpacker website (with the following API in .Net? Because somehow I don't understand the authorization towards their server...
The code I'm currently using is the following:
private readonly HttpWebRequest _httpWebRequest = (HttpWebRequest)
WebRequest.Create("https://tagpacker.com/api/users/{YourUserID}/tags");
public void Load()
{
_httpWebRequest.ContentType = "application/json";
_httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(_httpWebRequest.GetRequestStream()))
{
var json = "{\"user\":\"test\"," +
"\"password\":\"bla\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)_httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
But I'm getting back the following message:
{
"status": 401,
"message": "User not authorized",
"code": "USER_NOT_AUTHORIZED",
"url": "/unauthorizedHandler"
}
The only thing else you get from them is an "API-Access" code like the following: 1b3f314dd132b0015b5415b1:bd0ffe4b-a01e-4bf5-b1ed-12b24145d12d where the first part is your user id and the second is your API-code I guess? Does anyone have an idea on how to use this? Tagpacker's Api FAQs are here.
Official answer from the tagpacker team is that you need to set the api key in the header like the following (Java example):
URL url = new URL("https://tagpacker.com/api/users/<your_user_id>/links?limit=20");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("api_key", "<your_api_key>");
I will try to do this in C# and edit the answer again afterwards.

How to get User json data with google Oauth2

I'm attempting to send back my token to request further information about the user logging in. I want to get json back.
using the code below I get an exception "The given key was not present in the dictionary."
What am I doing wrong?
public void Login(Action<Mobile.Google.Account> googleLoginCompleted, Action googleLoginFailed)
{
var auth = new OAuth2Authenticator(
clientId: "myid",
clientSecret: "secret",
scope: "https://www.googleapis.com/auth/plus.login",
authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/v2/auth"),
redirectUrl: new Uri("http://adults.wicareerpathways.org"),
accessTokenUrl: new Uri("https://www.googleapis.com/oauth2/v4/token"));
auth.Completed += (sender, e) =>
{
if (e.IsAuthenticated)
{
var values = e.Account.Properties;
var access_token = values["access_token"];
var googleAccount = new Mobile.Google.Account
{
Username = e.Account.Username,
Properties = e.Account.Properties
};
try
{
var request = HttpWebRequest.Create(string.Format(#"https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + access_token + "&format=json", ""));
request.ContentType = "application/json";
request.Method = "GET";
var user_ID = values["user_id"];
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
System.Console.Out.WriteLine("Stautus Code is: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
GoogleAccountDetails result = Newtonsoft.Json.JsonConvert.DeserializeObject<GoogleAccountDetails>(content);
googleAccount.Username = result.id;
if (googleLoginCompleted != null)
{
googleLoginCompleted(googleAccount);
}
}
}
}
catch (Exception exx)
{
System.Console.WriteLine(exx.ToString());
}
}
Rather than directly solving your problem, let me give you some advice on how to solve this yourself.
It seems obvious that a key isn't present. The first important thing is to figure out which line exactly the problem is. I see two possibilities, "user_id" and "access_token". One of those two items must not be included. Both come from values. Try printing out values, and see what you come up with. In particular, print the keys, and see if you have a typo.
Looking at your code, I suspect your error is in the second, var user_ID = values["user_id"]; First of all, you don't seem to use it anywhere. Secondly, it is different than the clientId used earlier. In fact, I would suggest just using clientId, if that is what you intend, which will give you consistency in your requesting values.

HttpClient.PostAsync: API is returning missing parameter

I am trying to do a post with HttpClient to a standard REST API. The post method I am targeting requires two key/value pairs, name and size. When I perform the post using the code below, the API returns the error "Required keys missing: size." However, I've clearly added it to the FormUrlEncodedContent.
I'm wondering if there is an encoding issue, or if I am using one of wrong types of HttpContent.
public async Task<OHDrive> Create(OHDrive drive)
{
string json = "";
var values = new Dictionary<string, string>();
//name and size are required
if (string.IsNullOrEmpty(drive.Name) || drive.Size == 0)
throw new Exception("Name and Size are required for drive creation");
values["name"] = drive.Name;
values["size"] = drive.Size.ToString();
if (drive.UserID != null)
values["user"] = drive.UserID;
if (drive.Encryption != null)
values["encryption:cipher"] = drive.Encryption;
var content = new FormUrlEncodedContent(values);
using (HttpClient client = OHUtilities.CreateClient(userID, secretKey))
{
var url = urlBase + "create";
var response = await client.PostAsync(url, content);
json = await response.Content.ReadAsStringAsync();
}
return JsonConvert.DeserializeObject<OHDrive>(json);
}
Update:
I tried switching the order of the key/value pairs, like this:
values["size"] = drive.Size.ToString();
values["name"] = drive.Name;
I then got the opposite error message: "Required keys missing: name." It's like the API is not seeing the second param for some reason. I checked the request in Fiddler and everything appears to be correct.

Categories

Resources