Increase Your API Adoption with Gemini: Streamlining Developer Onboarding (Part 1/2)

Johannes H.B.
10 min readMay 10, 2024

--

1. Introduction

The success of your Application Programming Interface (API) is directly tied to its adoption by developers (or API consumers). A well-crafted API Developer Portal is a critical starting point, offering API documentation, guides, and references. But in the fast-paced world of software development, simply providing information isn’t enough. Developers are eager to get hands-on and see results quickly. That’s where Gemini comes in.

By integrating Gemini, Google’s advanced AI model, into your API strategy, you can transform the developer onboarding experience. Gemini will allow you to automate the creation of comprehensive “Get Started” tutorials packed with ready-to-use code snippets for your APIs. This will dramatically shorten the “time to Hello World” — the crucial interval between a developer discovering your API and successfully making their first API call.

Why is this so important? A swift “time to Hello World” experience:

  • Captures Developer Interest: Developers are more likely to stick with your API if they can achieve a quick win.
  • Demonstrates Value: A working example provides immediate proof of your API’s capabilities.
  • Builds Momentum: Early success encourages developers to explore further and integrate your API into their projects.
  • Reduces Frustration: Eliminating initial hurdles prevents developers from abandoning your API due to confusion or complexity.

Gemini acts as your onboarding accelerator, ensuring developers can swiftly grasp your API’s potential and put it to work. The result? Increased adoption, satisfied developers, and a thriving API ecosystem.

2. How Gemini Can Revolutionize your API Onboarding Process

Gemini excels at understanding the structure and capabilities of APIs defined by specifications like OpenAPI (formerly Swagger). By feeding your API specification into Gemini, you can:

  • Auto-Generate Tutorials: Gemini creates detailed, step-by-step guides that walk developers through common use cases.
  • Generate Code Snippets: Gemini produces accurate, runnable code snippets in various programming languages (e.g., Python, Java, JavaScript).
  • Parse and Explain Inputs/Outputs: Gemini can help developers understand the structure of requests and responses, making integration smoother.

3. Practical Examples: Pet Store API with Apigee and Gemini

Let’s illustrate Gemini’s power with two hands-on examples using the Pet Store Open API Specification (available here). We’ll cover the following:

  • Create a Pet Store API in the Google Apigee API Management Platform
  • Use Gemini Advanced to generate “Get started” tutorials in Python for this API using basic and advanced prompts

Let’s get started!

3.1 Creating an API Proxy in Apigee

We begin by importing our Pet Store Open API Spec into Apigee, and creating an API proxy. If you are not familiar with Apigee see the tutorial here for further information.

“Pet Store API proxy” deployed in Apigee

In Apigee, let´s add the “API key verification” policy to enhance the security of our API proxy. You can add further Apigee policies if needed, see the complete list of policies here.

Deploy your API proxy by clicking on “Deploy.”

Next, let’s update our OpenAPI specification by adding our Apigee API proxy’s endpoint (https://base_url/proxy_base_path). Additionally, we need to include a "securityScheme" in the OpenAPI Specification to indicate that an API key is required as a query parameter

Below is the final OpenAPI Specification that will be used in the next steps.

openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: https://base_url/proxy_base_path #REPLACE IT WITH YOUR PROXY ENDPOINT

paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
security:
- ApiKeyAuth: []
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
maximum: 100
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
security:
- ApiKeyAuth: []
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
required: true
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
security:
- ApiKeyAuth: []
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
maxItems: 100
items:
$ref: "#/components/schemas/Pet"
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string
securitySchemes:
ApiKeyAuth: # Arbitrary name for the security scheme
type: apiKey
in: query # The API key will be sent as a query parameter
name: apikey

Last but not least, verify your Open API Specification. As shown in the screenshot below, I uploaded to https://editor.swagger.io/ to make sure there are no errors.

Now we are ready to prompt Gemini to process our OpenAPI Spec to generate Python code snippets demonstrating how to call our API endpoints, handle authentication, and parse responses.

3.2 Example 1: Unleash Gemini Capabilities (basic prompt)

Gemini is very creative. The outcome you get depends a lot on the quality of your prompt. In this example, I will use a very basic prompt as shown below.

You are an experienced API Developer with a strong background in Python. 
You will be provided with an OpenAPI Specification 3.0 of my API and your task is to generate a "get started" tutorial that clearly demonstrate how to use the API .
You need to provide code snippets in Python for calling each API endpoints, processing and explaining responses.
Here is the OpenAPI spec: {INSERT YOUR OPEN API SPEC HERE }

Additional Notes:

  • You might consider asking Gemini to provide a table of contents or a brief outline of the tutorial before generating the full content. This can help ensure it aligns with your expectations.
  • If the API is large, you could break the tutorial into sections or focus on the most essential endpoints first.

The tutorial generated by Gemini is shown below.

Getting Started with the Swagger Petstore API (Python)

This guide walks you through interacting with the Petstore API to manage pet data. We’ll cover listing pets, creating new pets, and fetching details for a specific pet. Before you start, make sure you have your API key ready.

Prerequisites

  • Python: Installed on your system.
  • Requests Library: Install it using: pip install requests
  • API Key: Get your API key from the API provider (replace "YOUR_API_KEY" in the code below).

Code (use with caution)

import requests

base_url = "https://base_url/proxy_base_path" # REPLACE THIS WITH YOUR APIGEE PROXY ENDPOINT
api_key = "YOUR_API_KEY" #REPLACE WITH YOUR API KEY

# 1. List All Pets (GET /pets)
def list_pets(limit=10):
"""Fetches a list of pets, optionally limiting the number returned.

Args:
limit (int): Maximum number of pets to return (default 10, max 100).
"""
params = {"limit": limit, "apikey": api_key}
response = requests.get(f"{base_url}/pets", params=params)

if response.status_code == 200:
pets = response.json()
print("Pets:")
for pet in pets:
print(f" - ID: {pet['id']}, Name: {pet['name']}, Tag: {pet.get('tag', 'N/A')}")

# Check for next page link (if pagination is supported)
next_link = response.headers.get("x-next")
if next_link:
print(f"Next Page Link: {next_link}")
else:
print(f"Error: {response.status_code}, Message: {response.json().get('message', 'Unknown error')}")



# 2. Create a Pet (POST /pets)
def create_pet(name, tag=None):
"""Creates a new pet.

Args:
name (str): Name of the pet (required).
tag (str, optional): An optional tag for the pet.
"""

data = {"name": name}
if tag:
data["tag"] = tag

response = requests.post(f"{base_url}/pets?apikey={api_key}", json=data)

if response.status_code == 201:
print("Pet created successfully!")
else:
print(f"Error: {response.status_code}, Message: {response.json().get('message', 'Unknown error')}")



# 3. Get Pet Details (GET /pets/{petId})
def get_pet_details(pet_id):
"""Retrieves details for a specific pet.

Args:
pet_id (int): The ID of the pet.
"""

response = requests.get(f"{base_url}/pets/{pet_id}?apikey={api_key}")

if response.status_code == 200:
pet = response.json()
print("Pet Details:")
print(f" - ID: {pet['id']}, Name: {pet['name']}, Tag: {pet.get('tag', 'N/A')}")
else:
print(f"Error: {response.status_code}, Message: {response.json().get('message', 'Unknown error')}")

if __name__ == "__main__":
list_pets(limit=5)
create_pet("Buddy", tag="dog")
get_pet_details(1) # Assuming pet with ID 1 exists

How to Use It

  1. Insert API Key: Replace "YOUR_API_KEY" with your valid API key.
  2. Run: Execute the script. It will:
  • List the first 5 pets (or adjust the limit).
  • Create a new pet named “Buddy” with the tag “dog”.
  • Fetch and display details for the pet with ID 1 (if it exists).

You can tweak the prompt and evaluate Gemini’s output until you’re satisfied. Then, copy the generated content to your Developer Portal to enrich your API documentation.

3.3 Example 2: Unleash Gemini Capabilities (advanced prompt)

In this example, I’ll use a more elaborate/advanced prompt to demonstrate how a detailed prompt can yield better results from Gemini.

Here is my advanced prompt:

You are an expert API developer specializing in Python. 
Your task is to create a comprehensive "Get Started" tutorial using the OpenAPI Specification 3.0 (provided below).
Please focus on the following key elements:
Clear Explanations: Provide step-by-step instructions on how to use the API effectively.
Explain the purpose of each endpoint and the structure of requests and responses.

Python Code Snippets: Include well-structured, easy-to-understand Python code examples demonstrating how to interact with each API endpoint. Cover authentication, request formatting, error handling, and response parsing.
Response Interpretation: Guide users on how to interpret API responses, including handling different response codes, extracting relevant data, and utilizing it in their applications.
Best Practices: Incorporate API development best practices, security considerations, and potential optimizations for Python users.
Please note:
The target audience is Python developers who are new to this specific API.
Prioritize clarity, conciseness, and practical examples.
The tutorial should be self-contained, with minimal external dependencies.
OpenAPI Specification:
{INSERT YOUR OPEN API SPEC HERE }

As you can see, we provided Gemini with concise instructions and clear expectations. This approach helps Gemini generate a more accurate and relevant response.

Below is the “Get started” tutorial generated by Gemini:

Getting Started with the Swagger Petstore API (Python Tutorial)

This tutorial will walk you through using the Petstore API to manage information about your furry friends. We’ll cover everything from setup to advanced usage, with a focus on clear explanations and practical Python examples.

A. Setting Up Your Environment

  • Install Requests: We’ll use the requests library for making API calls:
pip install requests
  • Get Your API Key: You’ll need an API key (apikey) to authenticate your requests. Obtain this from the API provider or documentation.

B. Listing All Pets (GET /pets)

import requests

base_url = "https://base_url/proxy_base_path" # REPLACE WITH YOUR APIGEE PROXY ENDPOINT
api_key = "YOUR_API_KEY" # Replace with your actual API key

params = {
"apikey": api_key,
"limit": 25 # Optional: Limit the number of results (max 100)
}

response = requests.get(f"{base_url}/pets", params=params)

if response.status_code == 200:
pets = response.json()
print(pets) # Print the list of pets

# Check for the 'x-next' header for pagination
next_page_url = response.headers.get("x-next")
if next_page_url:
print(f"Next page: {next_page_url}")
else:
error = response.json()
print(f"Error: {error['code']}: {error['message']}")

Explanation:

  • We construct the API endpoint URL.
  • params is a dictionary containing the API key and optional limit.
  • We send a GET request using requests.get().
  • We check the status code: 200 means success, others indicate errors.
  • If successful, we parse the JSON response into a list of pets.
  • We handle pagination by checking the x-next header.
  • Error handling is crucial; print informative messages for failed requests.

C. Creating a Pet (POST /pets)

import requests

base_url = "https://base_url/proxy_base_path" # REPLACE WITH YOUR APIGEE PROXY ENDPOINT
api_key = "YOUR_API_KEY" # Replace with your actual API key

new_pet_data = {
"id": 999, # Example ID, might be auto-generated by the server
"name": "Fluffy",
"tag": "cat" # Optional
}

headers = {"Content-Type": "application/json"}
params = {"apikey": api_key}

response = requests.post(
f"{base_url}/pets", params=params, headers=headers, json=new_pet_data
)

if response.status_code == 201:
print("Pet created successfully!")
else:
# ... (error handling similar to the GET example)
error = response.json()
print(f"Error: {error['code']}: {error['message']}")

Explanation:

  • We set up the new pet’s data.
  • We include the API key as a query parameter.
  • We set the Content-Type header to application/json.
  • json parameter auto-converts python dictionary into json
  • We use requests.post() to send the data.
  • We handle success (201) and errors.

D. Getting a Specific Pet (GET /pets/{petId})

import requests

base_url = "https://base_url/proxy_base_path" # REPLACE WITH YOUR APIGEE PROXY ENDPOINT
api_key = "YOUR_API_KEY" # Replace with your actual API key

pet_id = 123 # Replace with the actual pet ID you want to retrieve

params = {"apikey": api_key}

response = requests.get(f"{base_url}/pets/{pet_id}", params=params)

if response.status_code == 200:
pet = response.json()
print(pet) # Print the details of the specific pet
else:
# Error Handling
if response.status_code == 404:
print(f"Error: Pet with ID {pet_id} not found.")
else:
error = response.json()
print(f"Error: {error['code']}: {error['message']}")

Best Practices and Security

  • Error Handling: Always include comprehensive error handling to gracefully manage unexpected API responses.
  • Input Validation: Validate user input before sending it to the API to prevent errors and security vulnerabilities.
  • Rate Limiting: Respect the API’s rate limits to avoid getting temporarily blocked.
  • Security: Never hardcode your API key. Consider using environment variables or a configuration file.

By comparing Example 1 ( basic prompt) and Example 2 ( advanced prompt), you can clearly see that refining and adding more detail to the prompt has significantly improved the quality and relevance of the output generated by Gemini.

4. Conclusion

Gemini is a powerful tool that can benefit API producers by improving documentation and developer portals, thereby boosting developer adoption. But what if you have dozens or hundreds of APIs in your portfolio? In part 2 of this blog post, I’ll explore how to automate the process of generating “Get Started” tutorials for your APIs at scale, leveraging Gemini and other GCP services. Stay tuned!

For other examples of ways that Gemini can help API producers, see my previous post on how to use Gemini to quickly generate and test API mock backends.

If you found this content useful, I’d love to hear your thoughts or feedback below.

--

--