DEV Community

Phil IPS
Phil IPS

Posted on

Getting Started with the Gemini API: A Practical Guide

Getting Started with the Gemini API

The Gemini API offers advanced language capabilities that can be integrated into a wide range of applications, from chatbots to content generation. This tutorial will guide you through creating a simple request, understanding the response structure, and implementing a Python example.

Prerequisites

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

Endpoint Overview

The REST endpoint for generating text is:

https://generativelanguage.googleapis.com/v1beta1/models/gemini-pro:generate:json
Enter fullscreen mode Exit fullscreen mode

You send a POST request containing a JSON payload with the model name, prompt, and generation parameters such as temperature and max tokens.

Sample Request Payload

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

Python Implementation

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}")
Enter fullscreen mode Exit fullscreen mode

Interpreting the Response

The API returns a JSON object with a candidates array. Each candidate contains a content field with the generated text. Extract this field to use in your application.

Best Practices

  • Keep your API key secret; never hard‑code it in client‑side code.
  • Monitor usage to avoid unexpected costs.
  • Experiment with temperature and max_output_tokens to balance creativity and relevance.

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

Top comments (0)