I am attempting to integrate with the Eventbrite API, I am just trying to create an event using RestSharp.
// Request to create an event.
var restClient = new RestClient("https://www.eventbriteapi.com/v3/");
This is the base url I am using {MyOrganiserID} and MyToken to replace my actual token.
var createEventRequest = new RestRequest("organizations/{MyOrganiserID}/events", Method.POST);
createEventRequest.AddHeader("Authorization", "Bearer MyToken");
createEventRequest.AddHeader("content-type", "application/x-www-form-urlencoded");
createEventRequest.AddQueryParameter("event.name.html", "My Event is good mate");
createEventRequest.AddQueryParameter("event.start.utc", "2019-12-12T18:00:00Z");
createEventRequest.AddQueryParameter("event.start.timezone", "Australia/Melbourne");
createEventRequest.AddQueryParameter("event.end.utc", "2019-12-12T20:00:00Z");
createEventRequest.AddQueryParameter("event.end.timezone", "Australia/Melbourne");
createEventRequest.AddQueryParameter("event.currency", "AUD");
IRestResponse createEventRestResponse = restClient.Execute(createEventRequest);
var requestContent = createEventRestResponse.Content;
I have also tried to send the parameters in the requestbody using AddBody and AddXMLBody from the RestSharp API.
createEventRequest.AddBody("event.name.html=<p>A DARQ Room Production Woof Woof</p>&event.start.utc=2019-12-12T18:00:00Z&event.start.timezone=Australia/Melbourne&event.end.utc=2019-12-12T20:00:00Z&event.end.timezone=Australia/Melbourne&event.currency=AUD");
createEventRequest.AddXmlBody("event.name.html=<p>A DARQ Room Production Woof Woof</p>&event.start.utc=2019-12-12T18:00:00Z&event.start.timezone=Australia/Melbourne&event.end.utc=2019-12-12T20:00:00Z&event.end.timezone=Australia/Melbourne&event.currency=AUD");
I've also tried to add the fields via the AddParameters method as well.
createEventRequest.AddParameter("event.name.html", "This is a good event mate");
createEventRequest.AddParameter("event.start.utc", "2019-12-12T18:00:00Z");
createEventRequest.AddParameter("event.start.timezone", "Australia/Melbourne");
createEventRequest.AddParameter("event.end.utc", "2019-12-12T20:00:00Z");
createEventRequest.AddParameter("event.end.timezone", "Australia/Melbourne");
createEventRequest.AddParameter("event.currency", "AUD");
With the AddQueryParameter I get a 401 Unauthorised I have tried putting the token as a query parameter aswell and it still says I'm unauthorized.
And another error I get is
{
"status_code": 403,
"error_description": "You do not have permission to access the resource you requested.",
"error": "NOT_AUTHORIZED"
}
When I send the parameter via the request body.
Any help anyone can provide would be deeply appreciated.
Related
I'm trying to do a POST request in C#, using RestSharp, in Visual Studio 2022.
I tested the API using Postman, which was successful. The API requires a 64-bit encoded Basic Auth (which I have), and a unique API key (which I also have). I then looked at the C# Restsharp code provided by Postman, and tried to copy paste it into my VS project, but most of the libraries were deprecated. I then ended up modifying the code so it didn't give me any errors, and the code itself runs, but getting a semantic error: the request returns "Missing or Malformed URL parameters". In the body parameter, I send one parameter in the form
var body = #"{""fieldNameHere"": intHere}";
My full code (redacted):
var options = new RestClientOptions("URLHERE")
{
Timeout = -1
};
var client = new RestClient(options);
var request = new RestRequest
{
Method = Method.Post
};
request.AddHeader("API_KEY", "keyHere");
request.AddHeader("Authorization", "authHere");
request.AddHeader("Content-Type", "application/json");
var body = #"{""fieldNameHere"": intHere}";
request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
RestResponse response = await client.ExecuteAsync(request);
So I tried using a JObject for the parameter, got the same error, this is my code:
JObject jObjectBody = new JObject();
jObjectBody.Add("FieldName", intHere);
request.AddParameter("application/json", jObjectBody, ParameterType.RequestBody);
var clientValue = await client.ExecuteAsync(request);
I also tried using HttpWebRequest, but got an auth error so not sure what was going on there, didn't get that anywhere else. Would prefer to use RestClient anyway. This is the other way I tried to do the body parameter:
string postData = "{\"FieldNameHere\":" + intHere + "}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
I haven't found anything that works yet. If someone can guide me towards a solution I'd be mad grateful, thanks. It definitely seems to be the body giving me the issue.
Ah! For some reason, phrasing my body like this worked:
var body = new { FieldNameHere = intHere }
request.AddJsonBody(body);
I have no idea why this worked, but it did!
A list of things that DID NOT work:
JObject technique
switching header placement
encoding the auth myself
how the RR instantiation is set up
with and without explicitly saying application/json (also including the charset and excluding)
using HttpWebRequest instead of RestSharp
I'm attempting to pass username/password from an application to the API to receive a token authorization key. When I attempt to do so, I receive a 400 Bad Request error and I cannot figure out why. Below is the method in question:
public User UserAuthentication(string username, string password)
{
string endpoint = baseURL + "/TOKEN";
// Could be POST maybe
string method = "POST";
Credential jsonObj = new Credential
{
grant_type = "password",
username = username,
password = password
};
string jsonStr = JsonConvert.SerializeObject(jsonObj);
WebClient wc = new WebClient();
//x - www - form - urlencoded
wc.Headers[HttpRequestHeader.ContentType] = "application/x - www - form - urlencoded";
wc.Headers.Add("Access-Control-Allow-Headers", "content-type");
wc.Headers.Add("Access-Control-Allow-Origin", "*");
wc.Headers[HttpRequestHeader.Authorization] = "Bearer <token>";
wc.Headers.Add("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, OPTIONS");
string header = wc.Headers.ToString();
try
{
string response = wc.UploadString(endpoint, method, jsonStr);
return JsonConvert.DeserializeObject<User>(response);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I've messed around altering just about everything in this method in search of a fix.
What I've done:
/TOKEN was /values & /api/values
POST method was GET -- With this, I received a "Cannot send a content-body with this verb-type." error.
ContentType was changed to "application/json"
Access-Control-Allow-Origin had the baseURL
Checked the format of header & body:
Header:
{Content-Type: application/x - www - form - urlencoded
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Origin: *
Authorization: Bearer <token>
Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS}
Body:
{"grant_type":"password",
"username":"test#gmail.com",
"password":"password123"}
I obviously have something wrong in my request, I've just run out of ideas to try. I'm not entirely sure if UploadString() is the correct method to be using in this situation, but I couldn't find another method in the WebClient class that would be better. Any help to try and push me in the right direction would be very much appreciated.
So what I think you are trying to do is a form-urlencoded post to a "token" endpoint with a username/password grant. These are typically done like so:
using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://example.com/token"))
{
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "grant_type", "password" },
{ "username", "username#site.com" },
{ "password", "password12345" }
})
})
{
using (var resp = await _client.SendAsync(request))
{
resp.EnsureSuccessStatusCode();
//await resp.Content.ReadAsAsync<BearerToken>();
// for testing purposes, try this:
var returnData = await resp.Content.ReadAsStringAsync();
Console.WriteLine(returnData);
}
}
You should define this outside all scopes where you need to do Http requests:
private static readonly HttpClient _client = new HttpClient();
So, first off, try to stick with HttpClient. Other patterns such as WebClient are considered legacy.
Next, CORS headers are typically returned from the server when an OPTIONS call is sent to the server. You aren't doing that here, and you should never have to worry about that kind of stuff inside a C# program running from your computer. So you can drop the access-control header stuff.
Form-urlencoded data is not JSON data. It's a different way to format data. If you want to send JSON data, you should use the content-type application/json
Finally, you are trying to add an Authorization header. But that doesn't make much sense as you are trying to authenticate yourself to become authorized. If you send the right username/password, you will receive a bearer token that you can use in an Authorization header for future requests to said service.
Oh and I forgot to add: Whenever you see an error in the [400,499] range (in this case "400 - bad request") it means that you sent something wrong and the server doesn't understand what you are trying to do. For example: a 401 means you sent invalid or missing authorization information. A 400 means your data was probably malformed.
But I like your question... I can see what you were doing and you tried all kinds of different things.
Download a program called Fiddler if you want to see how HTTP works. It's a great tool to debug your HTTP calls.
I'm new to this so what I want to do is post an Ajax to campaign monitor to add a new subscriber to a my list. The issue here is that I've carried out the right procedures using Campaign Monitors documentation. However I get a 401 error on the response regarding that the request was not authenticated. I'm just wondering how would I use the API Key for this instance.
In JSON i am passing:
{ "Email Address": "test#test.com", "Name": "Test" }
Im passing this through by C#
using (var client = new HttpClient())
{
var response = await client.PostAsync("https://api.createsend.com/api/v3.1/subscribers/LISTID.json", new StringContent(senderInfo, Encoding.UTF8, "application/json"));
}
Is there something I'm meant to be passing through here?
Seems i was missing out the header for this response
I'm using the RestSharp API in a C# environment.
I've successfully built code that 1) returns a specific record, and 2) returns the most recent 50 records. As an example, the snippet below is the latter, which is working perfectly:
RestRequest request = new RestRequest();
request.Resource = "/sdpapi/request";
request.AddParameter("OPERATION_NAME", "GET_REQUESTS");
request.AddParameter("INPUT_DATA", #"<operation>
<details>
<from>0</from>
<limit>50</limit>
<filterby>All_Requests</filterby>
</details>
</operation>");
What I would like to do is update a single record on the server. The server's API says I must:
Provide a "request ID", to specify which record we'll be updating
Use an "operation name" of "EDIT_REQUEST"
Provide input data like so:
{
"operation": {
"details": {
"category": "hardware",
"subject": "test"
}
}
Attempt 1:
RestRequest request = new RestRequest();
request.Resource = "/sdpapi/request/{request_id}";
request.AddParameter("request_id", id, ParameterType.UrlSegment);
request.AddParameter("OPERATION_NAME", "EDIT_REQUEST");
request.AddParameter("INPUT_DATA", #"<operation>
<details>
<subject>test</subject>
<category>hardware</category>
</details>
</operation>");
Response comes back saying the connection was successful. Server shows a successful update attempt, however no changes are actually made. It's as if it hears my request, thinks I'm updating 0 variables.
Attempt 2:
Perhaps it is expecting the input data to be JSON.
RestRequest request = new RestRequest();
request.Resource = "/sdpapi/request/{request_id}";
request.AddParameter("request_id", id, ParameterType.UrlSegment);
request.AddParameter("OPERATION_NAME", "EDIT_REQUEST");
request.AddParameter("INPUT_DATA", #"{
""operation"": {
""details"": {
""category"": ""hardware"",
""subject"": ""test""
}
}");
This doesn't run. It comes back saying "Error when performing - EDIT_REQUEST - Content is not allowed in prolog."
Attempt 3:
I try adding the update parameters via the AddParameter() method.
RestRequest request = new RestRequest();
request.Resource = "/sdpapi/request/{request_id}";
request.AddParameter("request_id", id, ParameterType.UrlSegment);
request.AddParameter("OPERATION_NAME", "EDIT_REQUEST");
request.AddParameter("CATEGORY", "hardware");
request.AddParameter("SUBJECT", "test");
Returns the error "Error when parsing input XML elements - null - null".
Attempt 4:
A suggestion I saw online, to specify the content type and serialize my own JSON.
RestRequest request = new RestRequest();
request.AddHeader("Content-type", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddBody(new { category = "hardware", subject = "test" });
request.Resource = "/sdpapi/request/{request_id}";
request.AddParameter("request_id", id, ParameterType.UrlSegment);
request.AddParameter("OPERATION_NAME", "EDIT_REQUEST");
Returns the error "Error when parsing input XML elements - null - null".
Attempt 5:
request.Method = Method.PATCH;
I've tried various combinations using Method.PATCH, however it returns the error "The server does not support the functionality needed to fulfill this request (Method PATCH is not implemented by this servlet for this URI)."
Attempt 6:
request.Resource = "/sdpapi/request/{request_id}/category/hardware";
I've tried a few combinations of different URLs, however it returns the error "Error when validating URL - Invalid URL for the requested operation." Also the in-browser example I have to work with doesn't need to use a fancy URL. While it was a good test, I get the feeling this isn't the right direction.
I feel like I'm really close... but after hours of research, I have failed to resolve the matter.
It seems this instance was a case of using the wrong format. See Caramiriel's comment above, as they deserve all the credit.
I am creating application to access public emails in mailinator. I can view emails but I have difficulties when I am trying to delete them.
https://mailinator.com/apidocs.jsp all examples from documentacion worked except this one.
I have code to POST Http request:
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "msgid", id}
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.mailinator.com/api/delete?", content);
var responseString = await response.Content.ReadAsStringAsync();
}
Only error it throws is (405) Method Not Allowed. or Method is not supported by this URL.
So I guess either my url that I'm sending is bad, either my code.
I need some help to figure it out.
According to the API docs you need to pass a valid token with every call. The delete API example looks like this:
curl "https://api.mailinator.com/api/delete?id=1373143878-0-test22&token=..."
The elipsis (...) there needs to be a valid token. So, add the token to your values dictionary.