A RESTful API built with Node.js and Express.js that supports both MySQL and MongoDB databases. This API provides user registration/login functionality and full CRUD operations for product management.
- π User Management: Registration and Login (authentication not required as specified)
- π¦ Product Management: Full CRUD operations (Create, Read, Update, Delete)
- ποΈ Database Support: Both MySQL and MongoDB
- β Data Validation: Comprehensive input validation using Joi
- π§ Error Handling: Proper error responses and logging
- π± Flutter Ready: Perfect for Flutter mobile app integration
- Runtime: Node.js
- Framework: Express.js
- Databases: MySQL / MongoDB
- Validation: Joi
- Security: bcryptjs for password hashing
- Environment: dotenv for configuration
rest-api-flutter-nodejs/
βββ config/
β βββ database.js # Database connection configuration
βββ controllers/
β βββ userController.js # User-related business logic
β βββ productController.js # Product-related business logic
βββ models/
β βββ User.js # User model (MongoDB & MySQL)
β βββ Product.js # Product model (MongoDB & MySQL)
βββ routes/
β βββ userRoutes.js # User API routes
β βββ productRoutes.js # Product API routes
βββ validators/
β βββ validation.js # Input validation schemas
βββ .env # Environment variables
βββ package.json # Dependencies and scripts
βββ server.js # Main application file
βββ README.md # This file
-
Clone or download the project
-
Install dependencies:
npm install
-
Environment Setup:
- Copy
.envfile and configure your database settings - Choose between MySQL or MongoDB by setting
DB_TYPE
- Copy
-
Database Setup:
For MySQL:
- Create a database named
rest_api_db(or your preferred name) - Update MySQL connection details in
.env - Tables will be created automatically when the server starts
For MongoDB:
- Install MongoDB locally or use MongoDB Atlas
- Update
MONGODB_URIin.env - Collections will be created automatically
- Create a database named
Update the .env file with your database credentials:
# Choose database type
DB_TYPE=mysql # or mongodb
# MySQL Configuration
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=your_password
MYSQL_DATABASE=rest_api_db
# MongoDB Configuration (if using MongoDB)
# MONGODB_URI=mongodb://localhost:27017/rest_api_db# Development mode with auto-restart
npm run dev
# Production mode
npm startThe server will start on http://localhost:3000
- GET
/- API information and available endpoints
- POST
/api/users/register- Register a new user - POST
/api/users/login- Login user
- GET
/api/products- Get all products - GET
/api/products/:id- Get product by ID - GET
/api/products/search?q=query- Search products - POST
/api/products- Create new product - PUT
/api/products/:id- Update product - DELETE
/api/products/:id- Delete product
POST /api/users/register
Content-Type: application/json
{
"username": "johndoe",
"email": "john@example.com",
"password": "password123"
}POST /api/users/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "password123"
}POST /api/products
Content-Type: application/json
{
"name": "iPhone 15",
"price": 999.99,
"quantity": 50,
"description": "Latest iPhone model"
}PUT /api/products/1
Content-Type: application/json
{
"name": "iPhone 15 Pro",
"price": 1199.99,
"quantity": 30
}GET /api/productsGET /api/products/search?q=iPhoneusername(string, required, unique, 3-50 chars)email(string, required, unique, valid email)password(string, required, min 6 chars, hashed)createdAt(timestamp, auto-generated)updatedAt(timestamp, auto-updated)
name(string, required, 2-100 chars)price(number, required, positive)quantity(integer, required, min 0)description(string, optional, max 500 chars)createdAt(timestamp, auto-generated)updatedAt(timestamp, auto-updated)
All API responses follow this structure:
{
"success": true,
"message": "Operation successful",
"data": { ... },
"count": 10
}Error responses:
{
"success": false,
"message": "Error description",
"errors": ["Validation error details"],
"error": "Technical error (development only)"
}This API is designed to work seamlessly with Flutter applications. Use the http package in Flutter to make requests:
// Example Flutter code
import 'package:http/http.dart' as http;
import 'dart:convert';
class ApiService {
static const String baseUrl = 'http://localhost:3000/api';
// Register user
static Future<Map<String, dynamic>> register(Map<String, dynamic> userData) async {
final response = await http.post(
Uri.parse('$baseUrl/users/register'),
headers: {'Content-Type': 'application/json'},
body: json.encode(userData),
);
return json.decode(response.body);
}
// Get products
static Future<List<dynamic>> getProducts() async {
final response = await http.get(Uri.parse('$baseUrl/products'));
final data = json.decode(response.body);
return data['data'];
}
}The API includes comprehensive error handling:
- 400: Bad Request (validation errors)
- 401: Unauthorized (invalid credentials)
- 404: Not Found (resource doesn't exist)
- 409: Conflict (duplicate user)
- 500: Internal Server Error
For development, you can use:
npm run dev # Starts with nodemon for auto-restart- Password hashing with bcryptjs
- Input validation and sanitization
- SQL injection prevention (parameterized queries)
- NoSQL injection prevention (MongoDB)
- CORS enabled for cross-origin requests
- express: Web framework
- cors: Cross-origin resource sharing
- dotenv: Environment variable management
- bcryptjs: Password hashing
- joi: Data validation
- mysql2: MySQL driver
- mongoose: MongoDB ODM
- jsonwebtoken: JWT token handling (for future auth)
ISC License