Data API insert code 400

I’m trying to create a java service that uses the data api. I get a code 400 error without any message. I can insert data via curl using the same parameters.

java snip:
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse(“application/json”);

    RequestBody body = RequestBody.Companion.create(		"{\n    \"collection\":\"tableFoo\",\n    \"database\":\"dbFoo\",\n    \"dataSource\":\"clusterFOO\",\n    \"document\": {\"name\":\"test 4\"}\n\n}", mediaType);

    Request request = new Request.Builder()
      .url("https://us-west-2.aws.data.mongodb-api.com/app/foobar/endpoint/data/v1/action/insertOne")
      .addHeader("Content-type", "application/ejson")
      .addHeader("Accept", "application/json")
      .addHeader("apiKey", "XXX")
      .post(body)
      .build();
    String res = "";
    
try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code <p> " + " <p> " + response);
        }
        res = response.body().string();
    }
    return res;

java response:
Response{protocol=h2, code=400, message=, url=https://us-west-2.aws.data.mongodb-api.com/app/foobar/endpoint/data/v1/action/insertOne}

curl:

curl -s “https://us-west-2.aws.data.mongodb-api.com/app/FOOBAR/endpoint/data/v1/action/insertOne” -X POST -H “Content-Type: application/ejson” -H “Accept: application/json” -H “apiKey: XXX” -d ‘{“collection”: “tableFoo”, “document”: { “name”: “Hello2” }, “dataSource”: “clusterFoo”, “database”: “dbFoo” }’

Why is there no error message? why does the curl insert work, but not the java?

Hi there!

Since there wasn’t a reply to your message, I tried to run it by our documentation bot. Here is the response I got :slight_smile:


A 400 error in the MongoDB Data API typically indicates a bad request. Here are some common causes for this error when using the Data API in Java:

  1. Invalid JSON Format: Ensure that the JSON payload you are sending is correctly formatted. Any syntax errors in the JSON can result in a 400 error.
  2. Incorrect Endpoint or HTTP Method: Verify that you are using the correct endpoint and HTTP method (e.g., POST, GET) for the operation you are trying to perform.
  3. Missing or Incorrect Headers: Ensure that all required headers, such as Content-Type: application/json and any necessary authentication headers, are included and correctly formatted.
  4. Invalid Parameters: Check that all parameters in your request are valid and correctly formatted. This includes query parameters, path parameters, and body parameters.
  5. Authentication Issues: Ensure that your API key or other authentication credentials are correct and have the necessary permissions for the operation you are attempting.
  6. Data Validation Errors: If your request involves inserting or updating data, ensure that the data conforms to any schema validation rules defined in your MongoDB collection.

Here is a basic example of how you might structure a request to the MongoDB Data API in Java:

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MongoDBDataAPIExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://data.mongodb-api.com/app/<app-id>/endpoint/data/v1/action/insertOne");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("api-key", "<your-api-key>");
            conn.setDoOutput(true);

            String jsonInputString = "{ \"dataSource\": \"Cluster0\", \"database\": \"testDB\", \"collection\": \"testCollection\", \"document\": { \"name\": \"John Doe\", \"age\": 29 } }";

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            System.out.println("Response Code: " + responseCode);

        } catch (Exception e) {


Related Resources

FAQ
Connection Troubleshooting
Troubleshoot Connection Issues
Connecting to MongoDB in Java - Lesson 3: Troubleshooting a MongoDB Connection in Java Applications
Getting Started with MongoDB and Java - CRUD Operations Tutorial