I'm trying to call the google cloud API. Specifically, the language API from c# using the RestSharp library and OAuth 2. I'm able to successfully connect to the API using the curl call below:
curl -s -k -H "Content-Type: application/json" -H "Authorization: Bearer <access_token>"
https://language.googleapis.com/v1beta1/documents:annotateText
-d #c:\temp\entity_request.json > c:\temp\googleanalysis.json
I've tried several different ways of authenticating, but none of them so far have worked. My latest c# code looks like the following:
var client = new RestClient("https://language.googleapis.com");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("client-app", "<access_token>");
var request = new RestRequest("/v1beta1/documents:analyzeEntities", Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddFile("filename", #"c:\temp\entity_request.json");
var response = client.Execute(request);
var content = response.Content;
When I run this call from c# I get the following error back:
{
"error": {
"code": 403,
"message": "The request cannot be identified with a client project. Please pass a valid API key with the request.",
"status": "PERMISSION_DENIED"
}
}
My question is how do I properly call the google cloud API in RestSharp the way I am successfully with curl?
This works for me:
//obtenemos el token para las peticiones
string access_token = GetAccessToken(jsonFolder, new string[] { "https://www.googleapis.com/auth/cloud-platform" });
//peticiones hacia el rest de automl
var client = new RestClient("https://language.googleapis.com");
var request = new RestRequest("v1/documents:analyzeEntities", Method.POST);
request.AddHeader("Authorization", string.Format("Bearer {0}", access_token));
request.AddHeader("Content-Type", "aplication/json");
//seteamos el objeto
var aml = new AutoMLload_entities();
aml.document.content = text;
request.AddJsonBody(aml);
IRestResponse response = client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Related
I am trying to convert a post request presented via cURL to c# HTTPClient with an old application using .NETFramework4
The cURL notation of the request from API docs:
curl -X POST -H 'Authorization: Token token=sfg999666t673t7t82' -H 'Content-Type: multipart/form-data' -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' -F file=#/Users/user1/Downloads/download.jpeg -F file_name=nameForFile -F is_shared=true -F targetable_id=1 -F targetable_type=Lead -X POST "https://domain.freshsales.io/api/documents"
My C# code, currently taking a file the user uploaded via input type form and trying to upload:
var filename = String.Format("status_{0}", DateTime.Now.ToString("dd/MM"));
using (var content = new MultipartFormDataContent())
{
content.Add(new ByteArrayContent(file), "file", filename);
content.Add(new StringContent(filename), "file_name");
content.Add(new StringContent("true"), "is_shared");
content.Add(new StringContent(uID), "targetable_id");
content.Add(new StringContent("Contact"), "targetable_type");
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, $"documents") { Content = content };
return client.SendAsync(req).Result;
}
For now I always get BadRequest(400)
In PostMan I am able to get OK(201)..
For more reference this is the code PostMan presents for C# RestSharp (not sure how to fully translate if to HttpClient + byteArrayContent..
var client = new RestClient("mydomain.io/api/documents");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Token token=xxx");
request.AddFile("file", "/Users/user1/Desktop/sc.png");
request.AddParameter("targetable_id", "134");
request.AddParameter("targetable_type", "Contact");
request.AddParameter("name", "a.jpg");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I've set hallmonitor (OAuth 2.0 compliant service) in a Bronto sandbox, but using RestSharp I can't get the access token to be able to make further calls to the REST API.
I've been able to successfully use curl i.e.
curl -X POST -d "grant_type=client_credentials&client_id=CLIENTID&client_secret=CLIENTSECRET" https://auth.bronto.com/oauth2/token
I've tried a number of variations of the code below, but nothing seems to work, I always get an error response.
{
"error_description": "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method).",
"error": "unauthorized_client"
}
Simplified sample code
var client = new RestClient("https://auth.bronto.com");
client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
//client.Authenticator = new SimpleAuthenticator(CLIENT_ID, clientId, CLIENT_SECRET, secret);
RestRequest request = new RestRequest("/oauth2/token", Method.POST);
//request.AddHeader("Authorization", "Basic " + client);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter(GRANT_TYPE, CLIENT_CREDENTIALS);
//request.AddParameter(CLIENT_ID, clientId);
//request.AddParameter(CLIENT_SECRET, secret);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
Has anyone used RestSharp with Bronto REST API to successfully authenticate and get the access token?
Any help is much appreciated.
I am working on being able to have my custom chat bot to update my primary channel's title (status). I am following this post and I am trying to get the access_token from the REDIRECT_URI.
The URI that contains the redirect is:
https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&scope=channel_editor
I have manually tested this with my CLIENT_ID and REDIRECT_URI set to http://localhost and I get this response from the above URI (which is what I want):
http://localhost/#access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&scope=channel_editor
I am trying to get the access_token from this URI, but I cant seem to get to it from the code below. My response is:
https://api.twitch.tv/kraken/oauth2/authenticate?action=authorize&client_id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost&response_type=token&scope=channel_editor
Code:
string clientID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string redirectURL = "http://localhost";
string url = string.Format("https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id={0}&redirect_uri={1}&scope=channel_editor",
clientID, redirectURL);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirUrl = response.Headers["Location"];
response.Close();
// Show the redirected url
Console.WriteLine("You're being redirected to: " + redirUrl);
This is a console application
This is not directly related to c# but implementing it should be easy enough https://discuss.dev.twitch.tv/t/how-to-set-title/390/2
This twitch dev post helped me out until I got to the "Make the request" step. My problem was I needed to make the C# equivalent of this cURL command to change the channel's title:
curl -H 'Accept: application/vnd.twitchtv.v2+json'
-H 'Authorization: OAuth <access_token>'
-d "channel[status]=New+Status!&channel[game]=New+Game!"
-X PUT https://api.twitch.tv/kraken/channels/CHANNEL
Solution:
I decided to manually get the access_token from the authentication request by ctrl + c and ctrl + v the token from the URI given below and store it into my database:
http://localhost/#access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&scope=channel_editor
Then, I used Postman to generate my RestSharp code with the body request in JSON:
string accessToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var client = new RestClient("https://api.twitch.tv/kraken/channels/CHANNEL_NAME");
var request = new RestRequest(Method.PUT);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "OAuth " + accessToken);
request.AddHeader("accept", "application/vnd.twitchtv.v3+json");
request.AddParameter("application/json", "{\"channel\":{\"status\":\"Hello World\"}}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
I am getting a 400 bad request error when trying to connect to the Urban Airship Rest API. Below is the curl command I am trying to replicate in .NET. The .NET code is at the end. Please help.
curl -v -X POST
-u "username:passowrd"
-H "Content-type: application/json"
-H "Accept: application/vnd.urbanairship+json; version=3;"
--data '{"audience" : {"tag":"1_13_98"},
"device_types" : "all",
"notification" : {"alert": "Tag push alert"}
}'
https://go.urbanairship.com/api/push
The c# code I am trying to use is:
var json = gcm.ToJsonString();
Console.WriteLine("JSON GCM Message: " + json);
var uri = new Uri("https://go.urbanairship.com/api/push/?");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Credentials = new NetworkCredential(username, master);
request.ContentType = "application/json";
WebHeaderCollection myWebHeaderCollection = request.Headers;
myWebHeaderCollection.Add(HttpRequestHeader.Accept, "application/vnd.urbanairship+json; version=3;");
request.ContentLength = encoding.GetByteCount(json);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(json), 0, encoding.GetByteCount(json));
stream.Close();
var response = request.GetResponse();
response.Close();
}
return true;
The API for urbanAirship can be found here:
http://docs.urbanairship.com/reference/api/v3/push.html
And here is an example request..
POST /api/push HTTP/1.1
Authorization: Basic <master authorization string>
Content-Type: application/json
Accept: application/vnd.urbanairship+json; version=3;
{
"audience" : {
"device_token" : "998BAD77A8347EFE7920F5367A4811C4385D526AE42C598A629A73B94EEDBAC8"
},
"notification" : {
"alert" : "Hello!"
},
"device_types" : "all"
}
I've created a c# .Net library for talking to Urban Airship API V3
You can find it here:
https://github.com/JeffGos/urbanairsharp
Hope it helps
Instead of using the header collection (which is throwing an exception) try setting the Accept property on the Request object, e.g. request.Accept = "application/vnd.urbanairship+json; version=3;"
If you still get a 400, try looking in the response body for more details.
I am using RestSharp api to post text/images into tumblr. I have this piece of code which I had used to post data into tumblr. It used to post data successfully into tumblr
var restClient = new RestClient("http://tumblr.com/api/write");
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("email", "xxxxx#abc.com");
request.AddParameter("password", "whatever");
request.AddParameter("type", "regular");
request.AddParameter("title", "My post to tumblr");
request.AddParameter("body", "<b>I am now on tumblr");
IRestResponse response = restClient.Execute(request);
But now when I am testing it, it gets executed but posts nothing to tumblr. What am I missing here ?