Here is my code below. Getting the token from shopify works fine. However while creating a new product it keeps giving me an error. I’ve tried everything possible and it still does not work. Any advice would be appreciated.
Here’s how I call the CreateNewProduct method passing the access token from shopify and the shopname with the products endpoint.
CreateNewProduct(accessTokenDTO.access_token, "https://{myshopname}.myshopify.com/admin/api/2020-10/products.json");
Here’s the method below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{"product": { "title": "Burton Custom Freestyle 151", "body_html": "<strong>Good snowboard!</strong>", "vendor": "Burton", "product_type": "Snowboard", "tags": [ "Barnes & Noble", "John's Fav", "\Big Air\]}";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
2
Answers
There was an issue with the json not being formatted correctly and method was a PUT instead of POST. See working code below.
400 BadRequest normally refers to the body you are sending with your request is not valid according to the api.
Wheni look at your string that is supposed to be a json, it shows invalid data at the end.
You are missing closing quotes after Big Air. Also, not sure if those backslash are supposed to be there around Big Air but definitely the missing closing quotes would seem to be the issue