DEV Community

Subramanya K S
Subramanya K S

Posted on

Your First Steps to AI: Gemini API with FastAPI

Introduction

The AI world is changing rapidly, and Google is one of the pioneers in this revolution with Gemini. Gemini has the potential to understand and generate text, images, and code, thus changing the game for developers and innovators alike. Best part? You can already start playing with the open API for Gemini – for free!

Follow this article to dig in and let the Google Free Gemini API unleash its power in your next big thing!

Get Started

1. Getting Google Gemini API Key

For Google Gemini API, you'll need an active Google account to access Google AI Studio. If you don't have one, you can create one for free.

The easiest route to obtaining a Google Gemini API key is to go to Google AI Studio (aistudio.google.com) and log in to your Google account. On the home page or in the "API key" section, there is usually an option to "Get API Key" or "Create API Key." Possibly, you will be prompted to either select an existing Google Cloud project or create a new one (Firebase project is also fine). After some clicks and accepting the terms of service, your personal API key will be produced. Be sure to copy and keep it safe, as it's essential for authenticating your requests to the Gemini API.

2. Initializing FastAPI

FastAPI is a modern and high-performance python web framework used to build APIs quickly and efficiently.

To install FastAPI, you need to install python on your system. You can download it from Python's official website. After installing python on your system, run the below command in the terminal.

mkdir <your-project>
cd <your-project>
pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

or

create a python virtual environment and install the FastAPI.

mkdir <your-project>
cd <your-project>
python -m venv <your-virtual-environment-name>
source <your-virtual-environment-name>/bin/activate
pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

Note: Uvicorn is a lightning-fast ASGI (Asynchronous Server Gateway Interface) web server implementation for Python. It is designed to run asynchronous Python web applications.

3. Setting up the project

After installing FastAPI, inside the project folder create app.py or main.py (You can give any name of your choice). If you want, you can create .gitignore, Readme.md files.

Inside app.py write the code below to test if the FastAPI application is working.

from fastapi import FastAPI, HTTPException
import uvicorn

app=FastAPI()

@app.get('/')
async def read_root():
    return {"message": "Welcome to the Gemini API Caller."}

PORT=8000

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=PORT)
Enter fullscreen mode Exit fullscreen mode

You can run the code using below command inside virtual environment (if you have created) or in terminal

uvicorn app:app --reload   or uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

you can access the application in http://localhost:8000/

Let's integrate gemini api now.

4. Integrate Gemini API.

For integrating Gemini API with our FastAPI application, we need to install google-genai package.

pip install google-genai
Enter fullscreen mode Exit fullscreen mode

add the below code into your existing code.

from google import genai

client = genai.Client(api_key=API_KEY)

def gemini_response(prompt):  
    response = client.models.generate_content(
            model='gemini-1.0-flash',
            contents=prompt,
            config=types.GenerateContentConfig(
                system_instruction="your instructions",
                max_output_tokens=100,
                temperature=0.5,
      )
   )
   return response.text
Enter fullscreen mode Exit fullscreen mode

5. Build Your First Gemini Endpoint

After defining your Gemini API call function. we can create an API endpoint. Add the following code in app.py.

from pydantic import BaseModel

class PromptRequest(BaseModel):
    prompt: str

@app.post("/api/generate-response")
async def generate_response_endpoint(request: PromptRequest):
    try:
        response = gemini_response(request.prompt)
        return {"response": response}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error calling Gemini API: {e}")

Enter fullscreen mode Exit fullscreen mode

6. Test the API

You can test the API either by Postman or connecting with frontend or using curl.

curl -X POST http://127.0.0.1:8000/api/generate-response -H "Content-Type: application/json" -d '{"prompt": "Explain quantum computing"}'
Enter fullscreen mode Exit fullscreen mode

Note: For securing Gemini API Key use environment variable. You can use python-dotenv.

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, you have taken the first steps to an AI application by integrating the Google Gemini API with FastAPI. You learned how to set up a simple API, connect back to the Gemini API with your key, and build the endpoint that generates intelligent responses. From there you could expand the project to store chat history, handle errors, or even make a user interface. The sky is the limit—keep exploring!

Top comments (0)