Content-Moderation endpoint returns an invalid JSON err despite valid JSON input

Using Node.js

Code:

const text = 
{
"input": "your mom"
}

const moderator = await openai.createCompletion("text-moderation-latest", {
input: text
});

This input should seemingly work as the request is valid JSON (you can quite literally put the input in a JSON validator and it’ll validate it) however OpenAI returns this error which states it is not valid JSON.

We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not 
valid JSON. If you have trouble figuring out how to fix this, please send an email to support@openai.com and include any relevant code you'd like help with.)

If anyone knows a solution for this I would highly appreciate it. I also don’t mind sharing more detail or a better explanation if someone needs it.

1 Like

Hey there! While what you’re passing is valid JSON, it’s not in the format that the API expects. The JSON you’re passing in looks like this:

{
  "input": {
    "input: "your mom"
  }
}

What it’s expecting is your original value. So, two options to fix your code:

1:

const moderator = await openai.createCompletion("text-moderation-latest", text);

2:

const moderator = await openai.createCompletion("text-moderation-latest", {
input: "your mom"
});

However, neither of these looks correct, according to the API documentation. If you’re trying to do moderation, they have a dedicated endpoint for that now:

You’re attempting to use the “completions” endpoint, which is no longer recommended. That said, not sure there is a node.js function to call yet for that. You might have to do an HTTP request yourself.

Thanks for the answer

I didn’t realize the NodeJS package doesn’t yet support that endpoint so running it through completions was just my desperate effort

I ran it through an HTTP request with this code which worked perfectly:

    const fetch = require("node-fetch");

    API_URL = `https://api.openai.com/v1/moderations`

    const headers = 
    {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
    };

    const moderator = await fetch(API_URL, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({
    input: input,
    }),
    });

    const data = await moderator.json();

It would’ve been nice to know that the endpoint wasn’t yet supported in the NodeJS package without digging through GitHub pull requests but oh well.

1 Like

Yeah, I was guessing that it wasn’t available due to the fact that “node.js” is not one of the options when selecting the sample code in the API documentation.