Getting Started with the Gemini API

The Gemini API provides powerful language capabilities for building AI-driven applications. This tutorial walks you through creating a simple request, interpreting the response, and integrating it into a Python script.

Prerequisites

  • A Google Cloud project with the Gemini API enabled.
  • An API key with permission to access the generate endpoint.
  • Python 3.8+ and the requests library installed.

Setting Up the Request

The endpoint URL is:

https://generativelanguage.googleapis.com/v1beta1/models/gemini-pro:generate:json 

You send a POST request with a JSON payload containing the model, prompt, and generation parameters.

Example Payload

{ "model": "gemini-pro", "prompt": "Explain the significance of the Golden Ratio in mathematics.", "temperature": 0.7, "max_output_tokens": 256 } 

Making the Call with Python

import requests import json API_KEY = "YOUR_API_KEY" url = f"https://generativelanguage.googleapis.com/v1beta1/models/gemini-pro:generate:json?key={API_KEY}" payload = { "model": "gemini-pro", "prompt": "Explain the significance of the Golden Ratio in mathematics.", "temperature": 0.7, "max_output_tokens": 256 } response = requests.post(url, json=payload) data = response.json() if response.status_code == 200: print(data["candidates"][0]["content"]) else: print(f"Error: {response.status_code} – {data}") 

Interpreting the Response

The API returns a list of candidates. Each candidate contains the generated text. You can extract the content field and use it in your application.

Cleanup

Remember to keep your API key secure and rotate it if compromised. Monitor your usage to avoid unexpected charges.

Published on Dev.to – #AI #MachineLearning #API #Python