Trying to post array of products using c# httpClinet to shopify.But getting 400 bad request. Also tried to post array of product = new object like items, but also getting 400 code.
var arrayOfProducts = new
{
products = new[]
{
new
{
title = "qqwqw",
description = "test",
product_type = "Game",
vendor = "test"
},
new
{
title = "1233eewq",
description = "test",
product_type = "Game",
vendor = "test"
}
}
};
var resp = await http.PostAsync($"{_shopify.Path}/products.json", new StringContent(
JsonSerializer.Serialize(arrayOfProducts)
, Encoding.UTF8, "application/json"), stoppingToken);
Related
I tried to write mutation but it gives me error.
as
GraphQL.Client.Http.GraphQLHttpRequestException: 'The HTTP request
failed with status code InternalServerError
The code I wrote is this:
private async Task SendMutationAsync(string endPoint)
{
var options = new GraphQLHttpClientOptions
{
EndPoint = new Uri(endPoint),
MediaType = "application/json",
};
var httpClient = new HttpClient();
var client = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer(), httpClient);
var account = new Account
{
Id = 152,
Name = "a",
Street = "a",
PostalCode = 1,
City = "a",
};
var request = new GraphQLRequest
{
Query = "mutation{createAccount (id: 152, name: \"a\", street: \"a\", postalCode: 1, city: \"a\"){ id,name,street,postalCode,city}}",
OperationName = "createAccount",
Variables = new { id = account.Id, name = account.Name, street = account.Street, postalCode = account.PostalCode, city = account.City }
};
var response = await client.SendQueryAsync<dynamic>(request).ConfigureAwait(false);
}
I am quite new to programming and I am meant to make a post request to Taxdoo APi. I am using the latest version of RestSharp. I tried reading their documentation but the lack of example code has me, as a beginner, crying in a corner. Here's the problem:
The API expects an array of products with the following payload format:
{
"products": [
{
"description": "Couch Supreme red",
"productIdentifier": "redcouch123",
"commodityCode": "9394240000",
"purchasePrice": 3200,
"currency": "EUR"
},
{
"description": "Wood table",
"productIdentifier": "wt234bas",
"commodityCode": "9394220000",
"purchasePrice": 300,
"currency": "EUR"
}
]
}
How can I get the products : into the request?
I tried the request.AddParameter, the request.AddOrUpdateParameter, I tried letting RestSharp do the parsing with request.AddJsonBody but I am so lost. I get BadRequest Error every time.
My code so far:
namespace ConnectToApi
{
internal class Program
{
static void Main(string[] args)
{
var endpoint = new Uri("https://sandbox-api.taxdoo.com/products");
using (RestClient? restClient = new(endpoint))
{
var request = new RestRequest();
var authToken = ConfigurationManager.AppSettings["authToken"];
request.AddHeader("AuthToken", authToken);
MyProduct productOne = new MyProduct
{
Description = "Product 1",
ProductIdentifier = "GBP-120",
CommodityCode = "123456",
PurchasePrice = 40,
Currency = "USD"
};
MyProduct productTwo = new MyProduct
{
Description = "Product 2",
ProductIdentifier = "GBP-125",
CommodityCode = "789101112",
PurchasePrice = 20,
Currency = "USD"
};
List<MyProduct> productList = new();
productList.Add(productOne);
productList.Add(productTwo);
string json = JsonConvert.SerializeObject(productList,Formatting.Indented);
request.AddStringBody(json, DataFormat.Json);
var response = restClient.Execute(request);
}
}
}
The JSONString looks like so:
[
{
"description": "Product 1",
"productIdentifier": "GBP-120",
"commodityCode": "123456",
"purchasePrice": 40,
"currency": "USD"
},
{
"description": "Product 2",
"productIdentifier": "GBP-125",
"commodityCode": "789101112",
"purchasePrice": 20,
"currency": "USD"
}
]
If anyone could help or send me a ressource where to look that is beginner friendly, I would be really glad.
Cheers guys.
You don't need serialization, just a wrapping class:
public class Body
{
public List<MyProduct> Products { get; set; }
}
...
var body = new Body();
body.Products = productList;
request.AddStringBody(body, DataFormat.Json);
You need to add a product wraping around your list before serialization. And add Post to your request. You can use an anonymous class for example
var request = new RestRequest(endpoint, Method.POST);
....
var products = new { Products = productList};
string json = JsonConvert.SerializeObject(products);
request.AddStringBody(json, DataFormat.Json);
var response = restClient.Execute(request);
I'm trying to create a POST call using HttpClient that I have fully working in Postman. Here is the body I'm sending in Postman:
{
"searchType": "games",
"searchTerms": [
"mario"
],
"searchPage": 1,
"size": 20,
"searchOptions": {
"games": {
"userId": 0,
"platform": "",
"sortCategory": "popular",
"rangeCategory": "main",
"rangeTime": {
"min": 0,
"max": 0
},
"gameplay": {
"perspective": "",
"flow": "",
"genre": ""
},
"modifier": ""
},
"users": {
"sortCategory": "postcount"
},
"filter": "",
"sort": 0,
"randomizer": 0
}
}
I have this written as the following in C#:
var client = _httpClientFactory.CreateClient(HttpClients.HowLongToBeat.ToString());
var request = new HowLongToBeatRequest
{
SearchType = "games",
SearchTerms = searchTerm.Trim().Split(" "),
SearchPage = 1,
Size = 20,
SearchOptions = new SearchOptions
{
Games = new SearchOptionsGames
{
UserId = 0,
Platform = "",
SortCategory = "popular",
RangeCategory = "main",
RangeTime = new SearchOptionsGamesRangeTime
{
Min = 0,
Max = 0
},
Gameplay = new SearchOptionsGamesGameplay
{
Perspective = "",
Flow = "",
Genre = ""
},
Modifier = ""
},
Users = new SearchOptionsUsers
{
SortCategory = "postcount"
},
Filter = "",
Sort = 0,
Randomizer = 0
}
};
//var json = JsonSerializer.Serialize(request);
//var content = new StringContent(json, Encoding.UTF8, "application/json");
//var response = await client.PostAsync("api/search", content);
var response = await client.PostAsJsonAsync("api/search", request, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
return new HowLongToBeatResponse();
I have this set up as
The url I'm hitting is: https://www.howlongtobeat.com/api/search and I'm setting it up like so in my Startup.cs
services.AddHttpClient(HttpClients.HowLongToBeat.ToString(), config =>
{
config.BaseAddress = new Uri("https://www.howlongtobeat.com/");
config.DefaultRequestHeaders.Add("Referer", "https://www.howlongtobeat.com/");
});
I am passing this Referer header in my Postman collection as well.
Basically, I can't figure out why this code gets a 403 in C# but the Postman that I think is exactly the same is getting a successful response. Am I missing something?
Let me know if there's any missing info I can provide.
I solved my problem. The issue was that this specific API required a User Agent header specified.
I think the problem is here, The BaseAddress property needs to be suffixed (https://www.howlongtobeat.com/) with a forward slash and here you already set route as well, change it to
services.AddHttpClient(HttpClients.HowLongToBeat.ToString(), config =>
{
config.BaseAddress = new Uri("https://www.howlongtobeat.com/");
config.DefaultRequestHeaders.Add("Referer", "https://www.howlongtobeat.com/api/search");
});
And then
var response = await client.PostAsJsonAsync("api/search", request, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
Updated:
try this, here I have hard-coded the Base URL for testing purposes.
try
{
var data_ = JsonConvert.SerializeObject(root);
var buffer_ = System.Text.Encoding.UTF8.GetBytes(data_);
var byteContent_ = new ByteArrayContent(buffer_);
byteContent_.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string _urls = "https://www.howlongtobeat.com/api/search";
var responses_ = await _httpClient.PostAsJsonAsync(_urls, byteContent_);
if (responses_.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("[GetPrimeryAccount] Response: Success");
string body = await responses_.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
I am having a hard time converting this generic template of facebook to C#. I am not sure if i converted it right. Below is the code i tried but is not rendering on messenger. Thank you.
curl -X POST -H "Content-Type: application/json" -d '{
"recipient":{
"id":"<PSID>"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome!",
"image_url":"https://petersfancybrownhats.com/company_image.png",
"subtitle":"We have the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://petersfancybrownhats.com/view?item=103",
"webview_height_ratio": "tall",
},
"buttons":[
{
"type":"web_url",
"url":"https://petersfancybrownhats.com",
"title":"View Website"
},{
"type":"postback",
"title":"Start Chatting",
"payload":"DEVELOPER_DEFINED_PAYLOAD"
}
]
}
]
}
}
}
}' "https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>"
This is what i tried in c# but it is not working. I am not sure if i converted it the proper way. Any help would be appreciated thank you.
Activity previewReply = stepContext.Context.Activity.CreateReply();
previewReply.ChannelData = JObject.FromObject(
new
{
attachment = new
{
type = "template",
payload = new
{
template_type = "generic",
elements = new
{
title = "title",
subtitle = "subtitle",
image_url = "https://thechangreport.com/img/lightning.png",
buttons = new object[]
{
new
{
type = "element_share,",
share_contents = new
{
attachment = new
{
type = "template",
payload = new
{
template_type = "generic",
elements = new
{
title = "x",
subtitle = "xx",
image_url = "https://thechangreport.com/img/lightning.png",
default_action = new
{
type = "web_url",
url = "http://m.me/petershats?ref=invited_by_24601",
},
buttons = new
{
type = "web_url",
url = "http://m.me/petershats?ref=invited_by_24601",
title = "Take Quiz",
},
},
},
},
},
},
},
},
},
},
});
await stepContext.Context.SendActivityAsync(previewReply);
The elements and buttons attributes need to be lists. Take a look at the example template below.
var attachment = new
{
type = "template",
payload = new
{
template_type = "generic",
elements = new []
{
new {
title = "title",
image_url = "https://thechangreport.com/img/lightning.png",
subtitle = "subtitle",
buttons = new object[]
{
new {
type = "element_share",
share_contents = new {
attachment = new {
type = "template",
payload = new
{
template_type = "generic",
elements = new []
{
new {
title = "title 2",
image_url = "https://thechangreport.com/img/lightning.png",
subtitle = "subtitle 2",
buttons = new object[]
{
new {
type = "web_url",
url = "http://m.me/petershats?ref=invited_by_24601",
title = "Take Quiz"
},
},
},
},
},
}
},
},
},
},
},
},
};
reply.ChannelData = JObject.FromObject(new { attachment });
Note, you only need to add a share_contents element to your template if your main template is different from the template you are trying to share. Otherwise, your button can just be new { type = "element_share" }, which makes the template far less complex.
Also, be sure to Whitelist all of your URLs and make sure all of the image URLs work properly - a couple of them weren't working properly. The template won't render if the URLs aren't Whitelisted and image links are broken.
Hope this helps!
i want to retrieve all contacts based on account in sugarcrm rest api using C# .net
i have tried
json = serializer.Serialize(new
{
session = sessionId,
module_name = "accounts",
query = "",
order_by = "",
offset = "0",
select_fields = "",
link_name_to_fields_array = "",
max_results = "2000",
deleted = 0
});
values = new NameValueCollection();
values["method"] = "get_entry_list";
values["input_type"] = "json";
values["response_type"] = "json";
values["rest_data"] = json;
response = client.UploadValues(sugarUrl, values);
responseString = Encoding.Default.GetString(response);
var accountsList = serializer.Deserialize<Dictionary<string, dynamic>>(responseString);
i am able to get all accounts and contacts but i am not getting relations between them i.e which contact belong to which account
Thanks for help in advance
UPDATE :
object[] linkNameToFieldsArray = new object[1]
{
new object[2, 2]
{
{ "name", "contacts" },
{ "value", new string[2]
{ "id", "last_name"
}
}
};
json = serializer.Serialize(new
{
session = sessionId,
module_name = "accounts",
query = "",
order_by = "",
offset = "0",
select_fields = "",
link_name_to_fields_array = linkNameToFieldsArray , ***//just added this to get related records***
max_results = "2000",
deleted = 0
});
values = new NameValueCollection();
values["method"] = "get_entry_list";
values["input_type"] = "json";
values["response_type"] = "json";
values["rest_data"] = json;
response = client.UploadValues(sugarUrl, values);
responseString = Encoding.Default.GetString(response);
var accountsList = serializer.Deserialize<Dictionary<string, dynamic>>(responseString);
Assuming a SugarCRM 6.4 or 6.5 system and API version REST v4_1...
I don't know the C#/.NET syntax/lingo, but 'link_name_to_fields_array' needs to be an array with keys of module names (e.g. "Contacts") and values that are arrays of the fields you want. The JSON would look like this:
{
"session":"asdfasdfsrf9ebp7jrr71nrth5",
"module_name":"Accounts",
"query":"",
"order_by":null,
"offset":0,
"select_fields":[
"id",
"name"
],
"link_name_to_fields_array":[
{
"name":"contacts",
"value":[
"id",
"last_name"
]
}
],
"max_results":"2",
"deleted":false
}
Also - I wrote this to help non PHP-devs interact with this version of the API, since documention is largely PHP based. You may find it useful: https://gist.github.com/matthewpoer/b9366ca4197a521a600f