Skip to content

srinureddy7/genai-nodejs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Gemini AI API - Node.js Project

A simple, professional, and well-structured Node.js API that integrates with Google's Gemini AI for text generation. Built with Express.js and following OOP principles.

Node.js Express.js Gemini AI

πŸ“‹ Table of Contents

✨ Features

  • βœ… Clean OOP Architecture - Class-based implementation
  • βœ… RESTful API - Well-defined endpoints
  • βœ… Input Validation - Robust error handling
  • βœ… Rate Limiting Ready - Easy to add rate limiting
  • βœ… Professional Logging - Request/response tracking
  • βœ… Health Checks - API monitoring endpoint
  • βœ… Graceful Shutdown - Proper server termination
  • βœ… Environment Configuration - Secure API key management
  • βœ… Extensible Design - Easy to add new features
  • βœ… CORS Support - Cross-origin requests (if enabled)

πŸš€ Quick Start

Prerequisites

  • Node.js (v18 or higher)
  • npm (Node Package Manager)
  • Google Gemini API Key

Installation

# 1. Clone the repository
git clone <your-repo-url>
cd nodejs-gemini

# 2. Install dependencies
npm install

# 3. Create environment file
cp .env.example .env

# 4. Add your Gemini API key to .env
# Edit .env file and add: GEMINI_API_KEY=your_api_key_here

# 5. Start the server
npm start

# For development with auto-restart:
npm run dev

πŸ› οΈ Project Setup Step-by-Step

Option 1: Using This Repository

# Create a new project directory
mkdir gemini-ai-project
cd gemini-ai-project

# Initialize npm project
npm init -y

# Install required packages
npm install express @google/generative-ai dotenv

# Copy the provided code files
# (Copy all the files from this repository)

# Create .env file
echo "PORT=3000" > .env
echo "GEMINI_API_KEY=your_api_key_here" >> .env

# Start the server
npm start

Option 2: Manual Setup

# 1. Create project structure
mkdir -p src/{config,controllers,services,routes}
mkdir -p src/middleware

# 2. Initialize package.json
npm init -y

# 3. Install dependencies
npm install express @google/generative-ai dotenv

# 4. Create all the code files as per structure below
# 5. Add scripts to package.json

πŸ”‘ Getting Gemini API Key

Step 1: Create Google Cloud Project

  1. Go to Google Cloud Console
  2. Click on the project dropdown (top left)
  3. Click "New Project"
  4. Enter project name (e.g., "gemini-api-project")
  5. Click "Create"

Step 2: Enable Gemini API

  1. In Google Cloud Console, go to "APIs & Services" > "Library"
  2. Search for "Generative Language API"
  3. Click on "Generative Language API"
  4. Click "Enable"
  5. Wait for API to be enabled (takes a few seconds)

Step 3: Create API Key

Method A: Via Google AI Studio (Recommended)

  1. Go to Google AI Studio
  2. Click "Get API Key"
  3. Click "Create API Key"
  4. Select your project
  5. Copy the generated API key
  6. Store it securely

Method B: Via Google Cloud Console

  1. Go to "APIs & Services" > "Credentials"
  2. Click "Create Credentials" > "API Key"
  3. Copy the generated API key
  4. (Optional) Restrict the API key for security

Step 4: Add API Key to Project

# Create .env file
echo "GEMINI_API_KEY=your_actual_api_key_here" > .env
echo "PORT=3000" >> .env

⚠️ Important Security Notes:

  • Never commit .env file to version control
  • Add .env to .gitignore
  • Restrict API key usage in Google Cloud Console
  • Use environment variables in production

πŸ“ Project Structure

gemini-ai-project/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── index.js          # Environment configuration class
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   └── AiController.js   # Request handlers
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   └── GeminiService.js  # AI service layer
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── ai.routes.js      # Route definitions
β”‚   └── app.js               # Express app setup
β”œβ”€β”€ .env                      # Environment variables (create this)
β”œβ”€β”€ .env.example              # Example environment file
β”œβ”€β”€ .gitignore               # Git ignore file
β”œβ”€β”€ package.json             # Project dependencies
└── server.js               # Application entry point

πŸ“š API Documentation

Base URL

http://localhost:3000

Endpoints

1. GET / - Home & Documentation

curl http://localhost:3000/

Response:

{
  "message": "Gemini AI API is running",
  "endpoints": {
    "health": "GET /health",
    "ask": "POST /ask"
  }
}

2. GET /health - Health Check

curl http://localhost:3000/health

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "service": "Gemini AI API"
}

3. POST /ask - Ask a Question

curl -X POST http://localhost:3000/ask \
  -H "Content-Type: application/json" \
  -d '{"question": "Explain quantum computing"}'

Successful Response:

{
  "success": true,
  "question": "Explain quantum computing",
  "answer": "Quantum computing uses quantum bits...",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "model": "gemini-2.0-flash"
}

Error Responses:

  • No body: {"error": "Request body is required"}
  • No question: {"error": "Question field is required"}
  • Empty question: {"error": "Question cannot be empty"}
  • Server error: {"error": "Internal server error"}

πŸ’» Code Explanation

1. Entry Point (server.js)

// Creates and starts the Express server
// Handles graceful shutdown
// Manages application lifecycle

2. Configuration (src/config/index.js)

// Manages environment variables
// Validates required configurations
// Provides centralized config access

3. Express App (src/app.js)

// Sets up Express middleware
// Configures routes
// Handles errors and 404 responses

4. Routes (src/routes/ai.routes.js)

// Defines API endpoints
// Maps URLs to controller methods
// Can add middleware for authentication/validation

5. Controller (src/controllers/AiController.js)

// Handles HTTP requests/responses
// Validates input data
// Calls service layer
// Returns formatted responses

6. Service (src/services/GeminiService.js)

// Contains business logic
// Interacts with Gemini AI API
// Handles AI model communication
// Manages API errors and responses

πŸ§ͺ Testing the API

Using cURL

# Test health endpoint
curl http://localhost:3000/health

# Test with valid question
curl -X POST http://localhost:3000/ask \
  -H "Content-Type: application/json" \
  -d '{"question": "What is artificial intelligence?"}'

# Test error cases
curl -X POST http://localhost:3000/ask \
  -H "Content-Type: application/json" \
  -d '{}'

curl -X POST http://localhost:3000/ask \
  -H "Content-Type: application/json" \
  -d '{"question": ""}'

Using Postman

  1. Setup:

    • Method: POST
    • URL: http://localhost:3000/ask
    • Headers: Content-Type: application/json
  2. Body (raw JSON):

{
  "question": "Explain machine learning"
}
  1. Expected Response: 200 OK with AI-generated answer

πŸ›‘οΈ Error Handling

The API handles various error scenarios:

  1. Validation Errors (400 Bad Request)

    • Missing request body
    • Missing question field
    • Invalid question type
    • Empty question
  2. Server Errors (500 Internal Server Error)

    • Gemini API failures
    • Network issues
    • Unexpected errors
  3. Client Errors (404 Not Found)

    • Invalid endpoints

All errors return consistent JSON responses for easy client-side handling.

πŸš€ Deployment

Local Development

npm run dev  # Auto-restart on changes

Production

npm start    # Run with Node.js

Using PM2 (Production Process Manager)

# Install PM2 globally
npm install -g pm2

# Start application
pm2 start server.js --name "gemini-api"

# Monitor application
pm2 monit

# View logs
pm2 logs gemini-api

# Restart application
pm2 restart gemini-api

Environment Variables for Production

PORT=3000
GEMINI_API_KEY=your_production_api_key
NODE_ENV=production

πŸ”§ Extending the Project

Adding New Features

  1. Add Authentication:
// In middleware/
class AuthMiddleware {
  static authenticate(req, res, next) {
    // Add JWT or API key authentication
  }
}
  1. Add Rate Limiting:
npm install express-rate-limit
  1. Add Database:
npm install mongoose  # For MongoDB
npm install pg       # For PostgreSQL
  1. Add Caching:
npm install redis
npm install node-cache

Adding More AI Models

// In GeminiService.js
class GeminiService {
  constructor(modelName = "gemini-2.0-flash") {
    this.model = this.ai.getGenerativeModel({ model: modelName });
  }

  async generateResponseWithModel(prompt, modelName) {
    const model = this.ai.getGenerativeModel({ model: modelName });
    // Generate response with specific model
  }
}

πŸ“Š Monitoring & Logging

Add Logging Middleware

// In app.js
app.use((req, res, next) => {
  const start = Date.now();
  res.on("finish", () => {
    const duration = Date.now() - start;
    console.log(`${req.method} ${req.path} ${res.statusCode} ${duration}ms`);
  });
  next();
});

Add Request ID for Tracing

const { v4: uuidv4 } = require("uuid");
app.use((req, res, next) => {
  req.requestId = uuidv4();
  next();
});

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit changes (git commit -m 'Add some AmazingFeature')
  4. Push to branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the ISC License - see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ“ž Support

For support, email or create an issue in the GitHub repository.


Made with ❀️ for learning and experimentation with Generative AI

Happy Coding! πŸš€

About

A simple, professional, and well-structured Node.js API that integrates with Google's Gemini AI for text generation. Built with Express.js and following OOP principles.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors