i'm making a console application to send email, im using the Qualtrics API REST, so i'm creating the request with RestSharp, the call that i'm using is for creating an email list, one of its parameters is the name of that list, but i want to put automatically the current date when it was created, this is the call:
static void Main(string[] args)
{
var client = new RestClient("https://qualtrics.com/API/v3/mailinglists");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "XXXX");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("X-API-TOKEN", "XXXX");
request.AddParameter("undefined", "{\r\n \"category\": \"Test Category\",\r\n \"libraryId\": \"XXXX\",\r\n \"name\": \"Application Test\"\r\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
}
This part: "name\": \"Application Test\" is what i want to modify to put in "Application Test" the current date, Is there a way to do this?
\"date\":" + DateTime.Today.ToString()
will give you want you want.
P.S. It would be better in future not to build your JSON by hand but to serialise it from a C# object.
Related
I want to send txt file to NAS device via FileStation API and I am coding in C#. When I posted request in Postman, request is successful and file is uploaded. But in C#, I use RestSharp Framework to post request. But I get error 101 or 401 in some situation. In below, I send my code. Thank you for your replies.
var client = new RestClient(url);
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
request.AddHeader("Cookie", "did="+_did+"; id="+_sid);
request.AddParameter("api", "SYNO.FileStation.Upload", ParameterType.RequestBody);
request.AddParameter("version", "3", ParameterType.RequestBody);
request.AddParameter("method", "upload", ParameterType.RequestBody);
request.AddParameter("path", "my_path", ParameterType.RequestBody);
request.AddParameter("create_parents", "False", ParameterType.RequestBody);
request.AddFile("filename", filename, "application/octet-stream");
var response = client.ExecutePostAsync(request).Result;
The last line of code is what is wrong. Because it is an Async call, you have to await it. However, that means the method this code is in needs to be marked as async. You aren't showing that code, so not sure if this is in the Main method or not. But ultimately, it should look like this:
public static async Task Main(params object[] parameters)
{
var client = new RestClient(url);
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
request.AddHeader("Cookie", "did="+_did+"; id="+_sid);
request.AddParameter("api", "SYNO.FileStation.Upload", ParameterType.RequestBody);
request.AddParameter("version", "3", ParameterType.RequestBody);
request.AddParameter("method", "upload", ParameterType.RequestBody);
request.AddParameter("path", "my_path", ParameterType.RequestBody);
request.AddParameter("create_parents", "False", ParameterType.RequestBody);
request.AddFile("filename", filename, "application/octet-stream");
var response = await client.ExecutePostAsync(request);
}
I have encountered the same problem, using Java, the server returns 101. If there is a solution, please let me know. Thank you.
I'm trying to convert this curl command to C# using RestSharp, and I'm having problems specifically with the data parameter (token and uri variables have been replaced w/dummy values for this example):
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'UserToken: usertoken' --header 'AppToken: apptoken' -d '[{"individualRecordNumber":"foo","score":"bar"}]' 'apiEndpoint'
I've been able to successfully do several GET requests within this same API, so I'm good with the overall request format and headers, I'm just having issues figuring out how to format the data and where to append it. Here's the rest of the request without the data:
var client = new RestClient(apiEndpoint);
var request = new RestRequest(Method.POST);
request.AddHeader("usertoken", usertoken);
request.AddHeader("apptoken", apptoken);
request.AddHeader("content-type", "application/json");
IRestResponse response = client.Execute(request);
I've tried using both AddParameter and AddJsonBody with various combinations of serialized and unserialized versions of the data.
Example of building data directly as string:
string examInfo = #"[{""individualRecordNumber"":""foo"",""score"":""bar""}]";
Example of building data as object:
object[] arrayObj = new object[1];
arrayObj[0] = new { individualRecordNumber = "foo", score = "bar" };
This is for a project with an extremely tight turnaround, so any help is much appreciated!
If you need a Post, to "wire in" the Post-Body, AddParameter has this overload
request.AddParameter("application/json", "mybody", ParameterType.RequestBody);
or , in your case
request.AddParameter("application/json", examInfo, ParameterType.RequestBody);
but maybe better (if you have later version)
request.AddJsonBody(new { A = "foo", B = "bar" });
And the initial constructor: (which you seem to have, but making sure to note it for future readers)
var request = new RestRequest(Method.POST);
More full example:
var client = new RestClient("https:blahblahblah");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
/* option1 */
request.AddParameter("application/json", "{mybody:'yes'}", ParameterType.RequestBody);
/* OR option 2 */
request.AddJsonBody(new { A = "foo", B = "bar" });
IRestResponse response = client.Execute(request);
I have a C# REST Web API and I have some code like this that makes a request to an endpoint. Some of the data that I want to pass along is an object of my own type and since it is a complex object, I would like to pass it using POST.
RestClient client = new RestClient(Constants.Endpoints.serviceEndPoint)
{
Timeout = 1000
};
string requestResource = Constants.Endpoints.apiEndPoint;
RestRequest request = new RestRequest(requestResource, Method.POST);
request.AddParameter("Authorization", $"Bearer {accessToken}", ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.AddParameter("id", id, ParameterType.UrlSegment);
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
On the other side, I am trying to read the object itself with some code like this
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var content in provider.Contents)
{
// what should I do here to read the content as a JSON
// and then transform it as the object it used to be before the call?
}
I tried to do await content.ReadAsJsonAsync< MyType>(); but also tried await content.ReadAsStringAsync(); and none of these worked. Am I doing something wrong at the time I execute in the client? Or is it something that I am doing on the other side while reading the content?
Instead of this line:
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
You should use the .AddBody(object) method.
So you're code would look like this:
RestRequest request = new RestRequest(requestResource, Method.POST);
//add other headers as needed
request.RequestFormat = DataFormat.Json;
request.AddBody(objectIWantToSerialize);
IRestResponse response = client.Execute(request);
On the server, if you're using MVC/WebAPI, you can just put the C# type as the input and ASP.NET will deserialize it for you. If not, can you provide more context about how you're receiving the request?
Below code I need to call in c#, how do we can achieve this, please help me.
import requests #requires "requests" package
import json
response = requests.post('https://scm.commerceinterface.com/api/v3/mark_exported', data={'supplier_id':'111111111', 'token':'sample-token',
'ci_lineitem_ids':json.dumps([54553919,4553920])}).json()
if response['success'] == True:
#Successfully marked as exported (only items which are not already marked exported)
pass
else:
pass
//I got sollution
C# post request
var client = new RestClient(exportUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddParameter("supplier_id", apiSupplierID);
request.AddParameter("token", apiToken);
request.AddParameter("ci_lineitem_ids", exportOrders);
IRestResponse response = client.Execute(request);
Similar to this forum post:
https://developer.citrixonline.com/forum/request-not-expected-format
However he didn't really explain what he found was wrong with his code.
I'm using RestSharp to make API calls. I've been able to get it to work great to pull an list of upcoming webinars however when I try to register participant I keep getting a 400/Request not in expected format error.
Following this documentation https://developer.citrixonline.com/api/gotowebinar-rest-api/apimethod/create-registrant, here is my code:
var client = new RestClient(string.Format("https://api.citrixonline.com/G2W/rest/organizers/{0}/webinars/{1}/registrants", "300000000000xxxxxx", btn.CommandArgument));
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json");
request.AddHeader("Accept", "application/vnd.citrix.g2wapi-v1.1+json");
request.AddHeader("Authorization", "OAuth oauth_token=" + System.Configuration.ConfigurationManager.AppSettings["GoToWebinar"]);
request.AddParameter("firstName", LoggedInUser.FirstName);
request.AddParameter("lastName", LoggedInUser.LastName);
request.AddParameter("email", LoggedInUser.Email);
var response = client.Execute(request);
var statusCode = response.StatusCode;
Any insights on how I can figure out why I keep getting that error?
Thank you!
Instead of using AddParamter (which adds key/value parameters to the request body), you need to write JSON instead:
request.DataFormat = DataFormat.Json;
request.AddBody(new {
firstName = LoggedInUser.FirstName,
lastName = LoggedInUser.LastName,
email = LoggedInUser.Email
});
You'll also need to clear the handlers (which automatically set the Accept header) if you want to specify them directly:
client.ClearHandlers();