Reputation: 27
According to the V3 Sendgrid documentation, I can create custom definitions using their API: https://docs.sendgrid.com/api-reference/custom-fields/create-custom-field-definition
My code is as follows:
public static async void addCustomDefinition(SendGridClient client)
{
var data = "{ 'name': 'test_name', 'field_type': 'Text' }";
var response = await client.RequestAsync(
method: SendGridClient.Method.POST,
urlPath: "marketing/field_definitions", //"contactdb /custom_fields",
requestBody: data
);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
}
However, I got the following output error message:
BadRequest {"errors":[{"field":"body","message":"invalid character '\'' looking for beginning of object key string"}]}
What am I doing incorrectly?
PS: I changed the urlPath
parameter:
...from online guide:
urlPath: "v3/marketing/field_definitions,
to this version:
urlPath: "marketing/field_definitions",
this newer version works for me on other commands such as getting field definitions and creating contact list
Upvotes: 1
Views: 598
Reputation: 7164
As you correctly stated, passing in the urlPath
prefixed with v3
doesn't work. This is because the SendGridClient
will prepend it for you automatically. You can pass in the version
named parameter to the constructor or use the Version
property on SendGridClient
to change the version that is prepended if needed.
It currently defaults to "v3"
.
The other issue is that the data
variable contains invalid JSON. In JSON single quotes are not allowed, and instead you have to use double quotes.
You can escape double quotes in a single-line string using a backslash:
var data = "{\"name\": \"custom_field_name\", \"field_type\": \"Text\"}";
You can escape double quotes in multi-line strings by adding extra double quote:
var data = @"{
""name"": ""custom_field_name"",
""field_type"": ""Text""
}";
Alternatively, you can create .NET objects and serialize them to a valid JSON string using System.Text.Json, JSON.NET, or other JSON libraries.
With these changes, your code should look like this:
public static async void addCustomDefinition(SendGridClient client)
{
var data = "{ \"name\": \"test_name\", \"field_type\": \"Text\" }";
var response = await client.RequestAsync(
method: SendGridClient.Method.POST,
urlPath: "marketing/field_definitions",
requestBody: data
);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
}
It looks like the SendGrid client library has undergone some changes that aren't reflected yet in the document you linked. This issue and the other issues in the doc will be fixed soon.
Let us know if this fixed your problem!
Upvotes: 2