3

I was attempting to insert a document into MongoDB Atlas, via the Data API.

However, the API kept returning the following error:

Header missing: please add content-type: application/json or application/ejson to specify payload data types.

This was unexpected. As you can see in the deluge script below, the "Content-Type" was specified in the header:

Original Code

// POST to MongoDB Data API 
headers = Map();
headers.put("Content-Type", "application/json");
headers.put("api-key", "API-KEY");
headers.put("Access-Control-Request-Headers", "*");

data = Map();
data.put("dataSource", "cluster");
data.put("database", "database");
data.put("collection", "names");

document = Map();
document.put("full_name", "Ari Adar");
data.put("document", document);

response = invokeurl
[
    url: "https://ap-southeast-2.aws.data.mongodb-api.com/app/data-***/endpoint/data/v1/action/insertOne"
    type: POST
    parameters: data.toString()
    headers: headers
];

alert response;

After some debugging, I eventually discovered that the error response from the Data API is inaccurate.

The solution is the script must convert the data map to a JSON string before passing it to the invokeURL function.

Working Code

// POST to MongoDB Data API 
headers = Map();
headers.put("Content-Type", "application/json");
headers.put("api-key", "API-KEY");
headers.put("Access-Control-Request-Headers", "*");

data = Map();
data.put("dataSource", "cluster");
data.put("database", "database");
data.put("collection", "names");

document = Map();
document.put("full_name", "Ari Adar");
data.put("document", document);

// Stringify the data map 
data_string = data.toString();

response = invokeurl
[
    url: "https://ap-southeast-2.aws.data.mongodb-api.com/app/data-***/endpoint/data/v1/action/insertOne"
    type: POST
    parameters: data_string
    headers: headers
];

alert response;

I hope this helps anyone else encountering the same error message. It would be great if MongoDB could update it.

1 Answer 1

0

Very good question. I managed to find also a thread on mongoapi website about it under this link:

Unable to POST, strange response.

So based on that I managed to fix it by changing following line in my http client:

MediaType mediaType = MediaType.parse("application/json");
RequestBody reqBody = RequestBody.create(body, mediaType);

And change those two into the following line:

RequestBody reqBody = RequestBody.create(body.getBytes(StandardCharsets.UTF_8));

But agree that the error log in my NetBeans seemed very strange:

Header missing: please add content-type: application/json or application/ejson to specify payload data types

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.