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.
- Features
- Prerequisites
- Quick Start
- Project Setup Step-by-Step
- Getting Gemini API Key
- API Documentation
- Project Structure
- Code Explanation
- Testing the API
- Error Handling
- Deployment
- Contributing
- License
- β 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)
- Node.js (v18 or higher)
- npm (Node Package Manager)
- Google Gemini API Key
# 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# 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# 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- Go to Google Cloud Console
- Click on the project dropdown (top left)
- Click "New Project"
- Enter project name (e.g., "gemini-api-project")
- Click "Create"
- In Google Cloud Console, go to "APIs & Services" > "Library"
- Search for "Generative Language API"
- Click on "Generative Language API"
- Click "Enable"
- Wait for API to be enabled (takes a few seconds)
Method A: Via Google AI Studio (Recommended)
- Go to Google AI Studio
- Click "Get API Key"
- Click "Create API Key"
- Select your project
- Copy the generated API key
- Store it securely
Method B: Via Google Cloud Console
- Go to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "API Key"
- Copy the generated API key
- (Optional) Restrict the API key for security
# Create .env file
echo "GEMINI_API_KEY=your_actual_api_key_here" > .env
echo "PORT=3000" >> .env- Never commit
.envfile to version control - Add
.envto.gitignore - Restrict API key usage in Google Cloud Console
- Use environment variables in production
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
http://localhost:3000
curl http://localhost:3000/Response:
{
"message": "Gemini AI API is running",
"endpoints": {
"health": "GET /health",
"ask": "POST /ask"
}
}curl http://localhost:3000/healthResponse:
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00.000Z",
"service": "Gemini AI API"
}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"}
// Creates and starts the Express server
// Handles graceful shutdown
// Manages application lifecycle// Manages environment variables
// Validates required configurations
// Provides centralized config access// Sets up Express middleware
// Configures routes
// Handles errors and 404 responses// Defines API endpoints
// Maps URLs to controller methods
// Can add middleware for authentication/validation// Handles HTTP requests/responses
// Validates input data
// Calls service layer
// Returns formatted responses// Contains business logic
// Interacts with Gemini AI API
// Handles AI model communication
// Manages API errors and responses# 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": ""}'-
Setup:
- Method: POST
- URL:
http://localhost:3000/ask - Headers:
Content-Type: application/json
-
Body (raw JSON):
{
"question": "Explain machine learning"
}- Expected Response: 200 OK with AI-generated answer
The API handles various error scenarios:
-
Validation Errors (400 Bad Request)
- Missing request body
- Missing question field
- Invalid question type
- Empty question
-
Server Errors (500 Internal Server Error)
- Gemini API failures
- Network issues
- Unexpected errors
-
Client Errors (404 Not Found)
- Invalid endpoints
All errors return consistent JSON responses for easy client-side handling.
npm run dev # Auto-restart on changesnpm start # Run with Node.js# 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-apiPORT=3000
GEMINI_API_KEY=your_production_api_key
NODE_ENV=production- Add Authentication:
// In middleware/
class AuthMiddleware {
static authenticate(req, res, next) {
// Add JWT or API key authentication
}
}- Add Rate Limiting:
npm install express-rate-limit- Add Database:
npm install mongoose # For MongoDB
npm install pg # For PostgreSQL- Add Caching:
npm install redis
npm install node-cache// 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
}
}// 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();
});const { v4: uuidv4 } = require("uuid");
app.use((req, res, next) => {
req.requestId = uuidv4();
next();
});- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add some AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the ISC License - see the LICENSE file for details.
- Google Gemini AI
- Express.js
- Node.js
- All contributors and users
For support, email or create an issue in the GitHub repository.
Made with β€οΈ for learning and experimentation with Generative AI
Happy Coding! π