pythonreact-nativegoogle-cloud-platformaxiosgoogle-gemini

Error 400: Invalid JSON payload received when calling Google Generative Language API


I'm having trouble with generating text using the Google Generative Language API. Specifically, I'm receiving a 400 Bad Request error with the message:

Invalid JSON payload received. Unknown name "prompt": Cannot find field.

or

Invalid JSON payload received. Unknown name "requests": Cannot find field. Details:

Endpoint: https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=YOUR_API_KEY

Request Payload (example):

json

{ "prompt": "Write a humorous caption related to: funny cat" }

Code Examples:

Node.js (Axios)

const axios = require('axios');

const API_KEY = 'YOUR_API_KEY'; // Replace with your API key

const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
const data = {
    prompt: "Write a humorous caption related to: funny cat"
};

axios.post(url, data, {
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(response => {
    console.log("Generated Text:", response.data);
})
.catch(error => {
    console.error('Error generating text:', error.response ? error.response.data : error.message);
});

Python (Flask)

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

API_KEY = 'YOUR_API_KEY'

@app.route('/generateText', methods=['POST'])
def generate_text():
    data = request.json
    prompt = data.get('prompt')

    if not prompt:
        return jsonify({"error": "Prompt is required"}), 400

    try:
        api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={API_KEY}"
        headers = {
            "Content-Type": "application/json"
        }
        json_data = {
            "prompt": prompt
        }
        response = requests.post(api_url, headers=headers, json=json_data)
        response_data = response.json()

        if response.status_code == 200:
            generated_text = response_data.get('candidates', [{}])[0].get('content', 'No text generated.')
            return jsonify({"text": generated_text})
        else:
            return jsonify({"error": response_data}), response.status_code

    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(port=5000)

Despite following the API documentation and removing unnecessary fields like requests, I still encounter these errors. I'm unsure how to correctly format the JSON payload or if there are other issues causing these errors.

What is the correct format for the JSON payload when using this API? Are there any additional requirements or parameters that need to be included?


Solution

  • When your showing Node.js and Python scripts are modified, how about the following modification?

    Node.js

    const axios = require("axios");
    
    const API_KEY = "###"; // Replace with your API key
    
    const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
    const data = {
      contents: [
        { parts: [{ text: "Write a humorous caption related to: funny cat" }] },
      ],
    };
    
    axios
      .post(url, data, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((response) => {
        console.log(
          "Generated Text:",
          response.data.candidates[0].content.parts[0].text
        );
      })
      .catch((error) => {
        console.error(
          "Error generating text:",
          error.response ? error.response.data : error.message
        );
      });
    

    When this script is run, the following result is obtained.

    Generated Text: ## Funny Cat Caption Ideas:
    
    **General:**
    
    * This is my life now. Just watching this cat try to figure out how to get into that box. 📦 😹
    * My cat is convinced that being a human is just a very inconvenient costume. 😹
    * I'm not sure what's funnier, the cat's face or the fact that they're trying to fit into a box that's clearly too small. 😂
    * They say you shouldn't laugh at someone's misfortune, but I'm pretty sure this cat doesn't mind. 😄
    
    **Specific:**
    
    * **Cat in a box:** "I'm not sure what's more impressive, this cat's ability to contort their body or their unwavering belief that they fit in this box." 🤯
    * **Cat with a strange expression:** "When you're trying to be subtle but your cat gives you the side-eye." 👀 😹
    * **Cat with a funny pose:** "I'm pretty sure my cat is auditioning for a yoga instructor." 🧘‍♀️😂
    
    **Bonus:**
    
    * **Punny:** "My cat is so fluffy, it's purr-fect." 😄
    * **Self-deprecating:** "My cat is proof that I am not the most intelligent being in this house." 😅
    
    **Remember to adjust the captions to fit the specific photo of your funny cat!** 😉
    

    Python

    from flask import Flask, request, jsonify
    import requests
    
    app = Flask(__name__)
    
    API_KEY = "###"
    
    
    @app.route("/generateText", methods=["POST"])
    def generate_text():
        data = request.json
        prompt = data.get("prompt")
    
        if not prompt:
            return jsonify({"error": "Prompt is required"}), 400
    
        try:
            api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={API_KEY}"
            headers = {"Content-Type": "application/json"}
            json_data = data = {"contents": [{"parts": [{"text": prompt}]}]}
            response = requests.post(api_url, headers=headers, json=json_data)
            response_data = response.json()
    
            if response.status_code == 200:
                generated_text = response_data.get("candidates", [{}])[0].get(
                    "content", "No text generated."
                )
                return jsonify({"text": generated_text})
            else:
                return jsonify({"error": response_data}), response.status_code
    
        except Exception as e:
            return jsonify({"error": str(e)}), 500
    
    
    if __name__ == "__main__":
        app.run(port=5000)
    

    When this script is run with {"prompt": "Write a humorous caption related to: funny cat"} using a curl command, the following result is returned.

    {"text":{"parts":[{"text":"## Funny Cat Caption Ideas:\n\n**General:**\n\n* \"My therapist told me to embrace my inner child. I think I found him. He's a cat and he's demanding tuna.\"\n* \"I'm not lazy, I'm just conserving my energy for important things like staring intensely at the wall.\" - Said every cat ever.\n* \"This is my cat. He's a professional at sleeping, eating, and judging me.\"\n\n**Image Specifics:**\n\n* **Cat stuck in a box:** \"This is my life now. Please send pizza.\"\n* **Cat with a funny expression:** \"You think you're having a bad day? I've seen things...\"\n* **Cat sleeping in a ridiculous position:** \"Gravity is for the weak. This is how I recharge.\"\n\n**Punny:**\n\n* \"He's not just a cat, he's a purr-sonality!\"\n* \"This cat is a real meow-sterpiece.\"\n* \"I'm paw-sitive this cat is plotting something.\"\n\n**Bonus:**\n\n* \"This is my cat, [cat's name]. He's the ruler of this house, and he's perfectly fine with that.\"\n\n**Remember to adapt the captions to your specific photo and add your own personal touch!** \n"}],"role":"model"}}
    

    Reference: