A comprehensive RESTful API for blog management built with Node.js and Express, featuring complete CRUD operations and secure authentication mechanisms. Perfect for learning backend development and building full-stack blog applications.
- Overview
- Features
- Tech Stack
- Project Structure
- Getting Started
- API Documentation
- Authentication Flow
- Database Models
- Middleware
- Error Handling
- Testing
- Contributing
- License
Blog API is a practice project designed to master CRUD (Create, Read, Update, Delete) operations and authentication in a Node.js environment. It provides a robust backend system for managing blog posts, user authentication, and authorization.
- Complete CRUD Operations: Create, read, update, and delete blog posts
- User Authentication: Secure registration and login system
- Authorization: Role-based access control
- JWT Tokens: Secure token-based authentication
- Password Encryption: Bcrypt password hashing
- Input Validation: Request data validation
- Error Handling: Centralized error management
- JWT token authentication
- Password hashing with bcrypt
- Protected routes
- Input sanitization
- CORS enabled
- Rate limiting (optional)
- Runtime: Node.js
- Framework: Express.js
- Database: MongoDB
- Authentication: JWT (JSON Web Tokens)
- Password Hashing: Bcrypt
- Validation: Express Validator
- Architecture: MVC Pattern
BlogApi/
βββ config/ # Configuration files (database, JWT settings)
βββ controllers/ # Request handlers and business logic
βββ database/ # Database connection and setup
βββ middlewares/ # Custom middleware (auth, validation, error handling)
βββ models/ # Database models/schemas
βββ routes/ # API route definitions
βββ utills/ # Utility functions and helpers
βββ .gitignore # Git ignore file
βββ example.js # Example usage/testing file
βββ package.json # Dependencies and scripts
βββ package-lock.json # Locked dependency versions
βββ server.js # Application entry point
- Node.js (v14.x or higher)
- npm or yarn
- MongoDB
- Postman (for API testing)
-
Clone the repository
git clone https://github.com/Oluwakemilola/BlogApi.git cd BlogApi -
Install dependencies
npm install
-
Set up the database
Ensure your database server is running and create a new database for the project.
Create a .env file in the root directory:
# Server Configuration
PORT=5000
NODE_ENV=development
# Database Configuration
DATABASE_URL=mongodb://localhost:27017/blogapi
# OR for PostgreSQL/MySQL
# DATABASE_URL=postgresql://user:password@localhost:5432/blogapi
# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_here
JWT_EXPIRE=7d
JWT_COOKIE_EXPIRE=7
# Email Configuration (optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_EMAIL=your_email@gmail.com
SMTP_PASSWORD=your_email_passwordDevelopment Mode:
npm start
# or with nodemon
npm run devProduction Mode:
npm run productionThe API will be available at http://localhost:5000
http://localhost:5000/api/v1
POST /auth/register
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "securePassword123",
"confirmPassword": "securePassword123"
}Response:
{
"success": true,
"message": "User registered successfully",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "123",
"name": "John Doe",
"email": "john@example.com"
}
}POST /auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "securePassword123"
}Response:
{
"success": true,
"message": "Login successful",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "123",
"name": "John Doe",
"email": "john@example.com"
}
}GET /auth/me
Authorization: Bearer {token}GET /auth/logout
Authorization: Bearer {token}GET /postsQuery Parameters:
page(optional): Page number for paginationlimit(optional): Number of posts per pagesort(optional): Sort field (e.g., -createdAt)
Response:
{
"success": true,
"count": 10,
"pagination": {
"page": 1,
"limit": 10,
"total": 50
},
"data": [
{
"id": "1",
"title": "My First Blog Post",
"content": "This is the content...",
"author": {
"id": "123",
"name": "John Doe"
},
"createdAt": "2024-01-22T10:00:00Z",
"updatedAt": "2024-01-22T10:00:00Z"
}
]
}GET /posts/:idPOST /posts
Authorization: Bearer {token}
Content-Type: application/json
{
"title": "My New Blog Post",
"content": "This is the content of my blog post...",
"tags": ["nodejs", "express", "tutorial"],
"category": "Technology"
}PUT /posts/:id
Authorization: Bearer {token}
Content-Type: application/json
{
"title": "Updated Title",
"content": "Updated content..."
}DELETE /posts/:id
Authorization: Bearer {token}GET /users/:idPUT /users/:id
Authorization: Bearer {token}
Content-Type: application/json
{
"name": "Updated Name",
"bio": "Software developer..."
}-
User Registration
- User submits registration form
- Password is hashed using bcrypt
- User data is saved to database
- JWT token is generated and returned
-
User Login
- User submits credentials
- Password is verified against hashed password
- JWT token is generated and returned
-
Protected Routes
- Client sends JWT token in Authorization header
- Middleware verifies token
- User data is attached to request object
- Route handler processes the request
// In your frontend or API client
const token = 'your_jwt_token_here';
fetch('http://localhost:5000/api/v1/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
title: 'My Post',
content: 'Post content...'
})
});{
id: ObjectId/UUID,
name: String (required),
email: String (required, unique),
password: String (required, hashed),
role: String (default: 'user'),
avatar: String,
bio: String,
createdAt: DateTime,
updatedAt: DateTime
}{
id: ObjectId/UUID,
title: String (required),
content: String (required),
author: ObjectId/UUID (ref: User),
tags: [String],
category: String,
published: Boolean (default: true),
views: Number (default: 0),
likes: Number (default: 0),
createdAt: DateTime,
updatedAt: DateTime
}{
id: ObjectId/UUID,
content: String (required),
author: ObjectId/UUID (ref: User),
post: ObjectId/UUID (ref: Post),
createdAt: DateTime,
updatedAt: DateTime
}Located in middlewares/auth.js, this middleware:
- Verifies JWT tokens
- Attaches user data to request object
- Protects routes from unauthorized access
const protect = async (req, res, next) => {
// Verify token and attach user to request
};const authorize = (...roles) => {
return (req, res, next) => {
// Check if user role is authorized
};
};Located in middlewares/validation.js:
- Validates request body data
- Sanitizes input
- Returns validation errors
Centralized error handling for consistent error responses.
The API uses a centralized error handling system:
{
"success": false,
"error": "Error message here",
"statusCode": 400
}| Code | Description |
|---|---|
| 200 | Success |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
- Import the API endpoints into Postman
- Set up environment variables (base URL, token)
- Test each endpoint with sample data
Check example.js for usage examples and testing scenarios.
npm testThis project demonstrates:
- β RESTful API design principles
- β CRUD operations implementation
- β JWT authentication and authorization
- β Password hashing and security
- β Middleware usage in Express
- β Database modeling and relationships
- β Error handling best practices
- β Input validation and sanitization
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch (
git checkout -b feature/NewFeature) - Commit your changes (
git commit -m 'Add NewFeature') - Push to the branch (
git push origin feature/NewFeature) - Open a Pull Request
This project is licensed under the MIT License.
Oluwakemilola
- GitHub: @Oluwakemilola
- Project Link: https://github.com/Oluwakemilola/BlogApi
- Built as a learning project for mastering CRUD operations and authentication
- Thanks to the Node.js and Express.js communities for excellent documentation
β Star this repository if you found it helpful for learning!
π¬ Questions or suggestions? Feel free to open an issue!