I’m having trouble with my Airtable API integration. When I try to POST a new record, I get a 422 error. Here’s what I’ve done:
async Task AddNewItem(ItemDetails details)
{
var endpoint = "https://api.airtable.com/v0/myAppId/Items";
var apiKey = "myApiKey";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var jsonData = JsonConvert.SerializeObject(details);
var content = new StringContent(jsonData);
try
{
var response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
Console.WriteLine("Item added successfully");
else
Console.WriteLine($"Error: {response.StatusCode}");
}
catch (Exception e)
{
Console.WriteLine($"Exception: {e.Message}");
}
}
}
My ItemDetails class has Name and ImageUrl properties. The API works fine in Postman, but not in my code. Any ideas what could be causing this? Thanks for your help!
hey there, i’ve run into this before. make sure ur json looks like this:
{“fields”:{“ImageUrl”:“https://example.com/image.jpg",“Name”:"Item Name”}}
also, set the content type header:
content = new StringContent(jsonData, Encoding.UTF8, “application/json”);
that shud fix it. lmk if u need more help!
I’ve encountered similar issues with Airtable’s API before. The 422 error typically indicates a problem with the request payload. Have you checked that your ‘content’ is properly formatted? It looks like you’re not setting the content type header.
Try modifying your code to include:
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
This ensures the content is sent as JSON. Also, double-check that your ‘details’ object matches Airtable’s expected structure exactly. The API can be quite particular about field names and types. If these don’t solve it, you might want to log the full response body for more detailed error information.
I’ve dealt with this exact issue before, and it can be frustrating. One thing that’s not immediately obvious from your code is how you’re structuring your JSON payload. Airtable expects a specific format for POST requests.
Try wrapping your serialized data in a ‘fields’ object like this:
var wrapper = new { fields = details };
var jsonData = JsonConvert.SerializeObject(wrapper);
Also, as Isaac_Cosmos mentioned, setting the content type is crucial. I’d go a step further and add this line:
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue('application/json'));
This explicitly tells Airtable you’re expecting JSON in return, which can sometimes help.
If you’re still having trouble, enable verbose logging on your HttpClient to see the exact request being sent. That often reveals subtle issues that are hard to spot otherwise.
Good luck with your integration!