Java implementation of Airtable POST request failing

I'm struggling to convert a cURL command to Java for an Airtable POST request. My code keeps throwing an error about invalid request body. Here's what I've tried:

String jsonPayload = "{" +
    "fields": {" +
        "\"Product\": \"itemID\", " +
        "\"Status\": \"InStock\" " +
    "}," +
    "\"applyTypeCasting\": true" +
"}";

void sendAirtableRequest() throws HttpException {
    HttpResponse<JsonNode> result = Unirest.post("https://api.airtable.com/v0/" + myBaseId + "/" + myTableName)
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer " + myApiKey)
        .body(jsonPayload)
        .asJson();
    System.out.println(result.getBody());
}

The error I'm getting is:
{"type":"INVALID_REQUEST_BODY","message":"Could not parse request body"}

What am I doing wrong? Any help would be great. Thanks!

Having worked extensively with Airtable’s API, I can confirm that JSON formatting is crucial. Your issue likely stems from improper string escaping. Instead of manual string concatenation, consider using a JSON library like Gson or Jackson. Here’s a quick example using Gson:

String jsonPayload = new Gson().toJson(Map.of(
“fields”, Map.of(
“Product”, “itemID”,
“Status”, “InStock”
),
“applyTypeCasting”, true
));

This approach ensures correct JSON formatting and escaping. Also, verify your API credentials and endpoint URL. Sometimes, API versioning changes can cause unexpected errors. If issues persist, enable detailed logging in your HTTP client for more insights.

I’ve run into similar issues with Airtable’s API before. The problem is likely in your JSON string construction. Java’s string concatenation can be tricky with JSON. Here’s a solution that worked for me:

Use a JSONObject to build your payload instead of a raw string. It’s much more reliable:

JSONObject fields = new JSONObject();
fields.put("Product", "itemID");
fields.put("Status", "InStock");

JSONObject requestBody = new JSONObject();
requestBody.put("fields", fields);
requestBody.put("applyTypeCasting", true);

String jsonPayload = requestBody.toString();

Then use this jsonPayload in your Unirest request. This approach ensures proper JSON formatting and escaping. It solved my invalid request body errors when working with Airtable’s API.

Also, double-check your API key and base/table IDs. Sometimes those can cause cryptic errors if they’re incorrect or expired.

yo, i’ve dealt with this before. ur json string is messed up. try using a json library like jackson or gson. it’ll make ur life way easier. something like:

JsonObject json = new JsonObject();
json.add(“fields”, new JsonObject());
json.getAsJsonObject(“fields”).addProperty(“Product”, “itemID”);
json.getAsJsonObject(“fields”).addProperty(“Status”, “InStock”);
json.addProperty(“applyTypeCasting”, true);

String jsonPayload = json.toString();

that should fix it. gl!