{"id":40615337,"url":"https://github.com/andreger/fastapi-google-gemini","last_synced_at":"2026-01-21T06:02:25.286Z","repository":{"id":245356408,"uuid":"817974336","full_name":"andreger/fastapi-google-gemini","owner":"andreger","description":"This repository provides the code for a lightweight Text Generation and Image Analysis API using FastAPI to interact with Google's Gemini API.","archived":false,"fork":false,"pushed_at":"2024-06-21T00:39:06.000Z","size":6,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-06-21T18:30:06.103Z","etag":null,"topics":["ai","artificial-intelligence","fastapi","google-gemini","python"],"latest_commit_sha":null,"homepage":"https://andregervasio.dev/post/build-a-text-generation-and-image-analysis-api-with-fastapi-and-gemini-ai","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andreger.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-20T20:55:58.000Z","updated_at":"2024-06-21T18:30:14.202Z","dependencies_parsed_at":"2024-06-21T18:30:11.251Z","dependency_job_id":null,"html_url":"https://github.com/andreger/fastapi-google-gemini","commit_stats":null,"previous_names":["andreger/fastapi-google-gemini"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/andreger/fastapi-google-gemini","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreger%2Ffastapi-google-gemini","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreger%2Ffastapi-google-gemini/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreger%2Ffastapi-google-gemini/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreger%2Ffastapi-google-gemini/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andreger","download_url":"https://codeload.github.com/andreger/fastapi-google-gemini/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreger%2Ffastapi-google-gemini/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28628701,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-21T04:47:28.174Z","status":"ssl_error","status_checked_at":"2026-01-21T04:47:22.943Z","response_time":86,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","artificial-intelligence","fastapi","google-gemini","python"],"created_at":"2026-01-21T06:02:24.662Z","updated_at":"2026-01-21T06:02:25.273Z","avatar_url":"https://github.com/andreger.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Build a Text Generation and Image Analysis API with FastAPI and Gemini AI\n\nThis tutorial guides you through creating an API using FastAPI that interacts with Google's Gemini AI models. The API will offer two main functionalities:\n\n* **generate_text:** This endpoint receives a text prompt and uses Gemini to generate text based on it.\n* **image_to_text:** This endpoint receives an image URL and uses Gemini to extract text from it.\n\n## About the author - André Gervásio\n\n20+ years of experience in software development. Bachelor's degree in Computer Science. Fullstack Software Engineer and Tech Lead in Java, Python, JS, PHP applications. Certified in Front-End, Back-End and DevOps technologies. Experienced in Scrum and Agile Methodologies. Solid knowledge in Databases and ORMs. Practical skills in Cloud Computing Services.\n\n## 1. Set Up Python and FastAPI\n\nBefore we start coding, make sure you have the necessary tools installed:\n\nCheck if Python is installed by running the following command in your terminal:\n\n  ```bash\n  python3 --version # or python --version\n  ```\n\n  If Python is installed, you'll see the version number. Otherwise, download it from [https://www.python.org/downloads/](https://www.python.org/downloads/).\n\nNext, create a directory for your project. In this example, we'll name it fastapi-google-gemini. Navigate to this directory and set up a virtual environment to manage project dependencies:\n\n  ```bash\n  mkdir fastapi-google-gemini\n  cd fastapi-google-gemini\n  python3 -m venv venv\n  ```\n\nActivate your virtual environment:\n\n\n  ```bash\n  source venv/bin/activate\n  ```\n\nNow, install FastAPI using pip:\n\n  ```bash\n  pip install fastapi\n  ```\n\n## 2. Integrate Google GenerativeAI Library\n\nThe Google GenerativeAI library allows us to interact with the Gemini API for generating responses.\n\nUse pip to install the library:\n\n  ```bash\n  pip install google-generativeai\n  ```\n\n* **Obtain a Gemini API key:**\n\nAn API key is required to use the GenerativeAI library. See this article to learn [how to generate a Gemini API key](http://localhost:13000/post/how-to-generate-a-gemini-api-key)\n\nWe'll use an environment variable for security. In your terminal, set the API key using a command like:\n\n  ```bash\n  export GENERATIVE_AI_KEY=\"YOUR_API_KEY_HERE\"\n  ```\n\nReplace `YOUR_API_KEY_HERE` with your actual key.\n\n## 3. Create a FastAPI App\n\nInside your project directory, create a new Python file named main.py.\n\n```python\nfrom fastapi import FastAPI\nimport google.generativeai as genai\nimport os\n\ngenai.configure(api_key=os.getenv(\"GENERATIVE_AI_KEY\"))\nmodel = genai.GenerativeModel(model_name=\"gemini-1.5-flash-latest\")\n\napp = FastAPI()\n```\n\nThis code sets up a FastAPI web application and configures it to interact with Gemini AI models. It imports libraries for building the API (FastAPI) and interacting with Gemini (google-generativeai). It also retrieves your Gemini API key from an environment variable for secure authentication.\n\n## 4. Create the generate_text endpoint\n\nIn the main.py file, import the required libraries.\n\n```python\nfrom pydantic import BaseModel\n```\n\nDefine a data model to represent a text input.\n\n```python\nclass TextInput(BaseModel):\n    prompt: str\n```\n\nCreate a new route for the generate_text endpoint.\n\n```python\n@app.post(\"/generate_text\")\ndef generate_text(input: TextInput):\n    \"\"\"Generates text based on the provided prompt.\"\"\"\n\n    response = model.generate_content(input.prompt)\n    return {\"generated_text\": response.text}\n```\n\n  This code receives a user prompt via a POST request. It then uses the `google-generativeai` library to interact with a Gemini text generation model and generate text based on the prompt. Finally, it returns the generated text as a JSON response.\n\nExpected input example:\n\n```json\n{\n  \"prompt\": \"What is the meaning of life?\"\n}\n```\n\n## 5. Create the image_to_text endpoint\n\nWe need to install pillow library for image processing. Install it using pip:\n\n```bash\npip install pillow\n```\n\nIn the main.py file, import the required libraries.\n\n```python\nimport urllib.request\nfrom PIL import Image\nimport tempfile\n```\n\nDefine a data model to represent an image input.\n\n```python\nclass ImageInput(BaseModel):\n    url: str\n```\n\nCreate a new route for the image_to_text endpoint.\n\n```python\n@app.post(\"/image_to_text\")\ndef image_to_text(input: ImageInput):\n    \"\"\"Extracts text from an image.\"\"\"\n\n    with tempfile.NamedTemporaryFile(delete=False) as temp_file:\n        urllib.request.urlretrieve(input.url, temp_file.name)\n        img = Image.open(temp_file.name)\n        response = model.generate_content([\"What is in this photo?\", img])\n    temp_file.close()\n\n    return {\"generated_text\": response.text}\n```\n\nThis function takes an image URL, downloads it to a temporary file, opens the image, uses a model to analyze it and generate text description, cleans up the temporary file, and returns the generated text.\n\nExpected input example:\n\n```json\n{\n  \"url\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/Tundra_in_Siberia.jpg/800px-Tundra_in_Siberia.jpg\"\n}\n```\n\n\n## 6. Run the FastAPI Server and Test the API\n\nRun the FastAPI development server using the following command in your terminal:\n\n```bash\nfastapi dev main.py  # for production use: fastapi run main.py\n```\n\nFastAPI automatically generates interactive documentation for your API using Swagger. To access the documentation, navigate to http://localhost:8000/docs in your web browser. This interface provides a user-friendly way to explore your API\n\nWithin the Swagger UI, you can directly test each endpoint by providing the necessary input data and clicking the \"Execute\" button. This allows you to verify if the API responds as expected for different inputs.\n\n## Conclusion\n\nThis tutorial has guided you through creating a FastAPI API that interacts with Google's Gemini AI models using the `google-generativeai` library. The API offers two functionalities: generating text based on prompts and extracting text from images. Remember to replace placeholders with your actual Gemini API key and project details. With this API and the testing methods mentioned above, you can ensure its functionality and leverage the power of Gemini to create innovative applications.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreger%2Ffastapi-google-gemini","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandreger%2Ffastapi-google-gemini","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreger%2Ffastapi-google-gemini/lists"}