Skip to content

ckissi/jsonplaceholder-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

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

Repository files navigation

πŸš€ JSONPlaceholder.dev

A super fast fake REST API powered by Bun + Elysia.js - JSONPlaceholder implementation.

✨ Features

  • πŸ”₯ Blazing Fast - Built with Bun and Elysia.js for maximum performance
  • πŸ“Š 6 Resource Types - Users, Posts, Comments, Albums, Photos, and Todos
  • πŸ”— Proper Relationships - Posts belong to users, comments belong to posts, etc.
  • 🌐 Full REST API - Supports GET, POST, PUT, PATCH, DELETE
  • 🎯 JSONPlaceholder Compatible - Drop-in replacement for testing and prototyping
  • πŸš€ CORS Enabled - Ready for frontend development
  • πŸ’Ύ In-Memory Storage - Data resets on restart, perfect for testing

πŸš€ Quick Start

# Install dependencies
bun install

# Configure environment (optional)
cp .env.example .env
# Edit .env as needed

# Start the server
bun run index.ts

The API will be available at http://localhost:3000

βš™οΈ Configuration

The API can be configured using environment variables. Create a .env file or set the following variables:

# CORS Configuration
DISABLE_CORS=1          # Set to 1 to disable CORS for maximum performance
                         # Set to 0 or remove for browser compatibility

# Cache Configuration
ENABLE_CACHE=1          # Set to 1 to enable caching, 0 to disable (default: enabled)
CACHE_TTL=300           # Cache TTL in seconds (default: 300 = 5 minutes)

# Data Updates Configuration
ENABLE_UPDATES=0        # Set to 1 for real data changes, 0 for fake responses (default: disabled)

# Server Configuration
PORT=3000               # Port to run the server on
NODE_ENV=development    # Environment mode

Performance vs Compatibility

  • For benchmarking/testing: Set DISABLE_CORS=1 and ENABLE_CACHE=1 for maximum performance
  • For frontend development: Keep CORS enabled (default) for browser compatibility
  • For cache control: Use ENABLE_CACHE=1 (default) for better performance, ENABLE_CACHE=0 for always fresh data
  • Cache duration: Adjust CACHE_TTL in seconds (default 300 = 5 minutes)

Read-Only vs Live Mode

  • Read-Only Mode (ENABLE_UPDATES=0): Perfect for public APIs - POST/PUT/PATCH/DELETE requests return realistic fake responses without actually modifying data
  • Live Mode (ENABLE_UPDATES=1): Full functionality with real data modifications - includes a /reset endpoint to restore initial data

Reset Functionality

When ENABLE_UPDATES=1, you can reset all data to the initial state:

curl -X POST http://localhost:3000/reset

This endpoint:

  • Only works when ENABLE_UPDATES=1
  • Clears all caches
  • Restores all resources to their original state
  • Returns a success confirmation with timestamp

Available Scripts

# Standard server (CORS enabled)
bun run start

# Optimized server (better performance, configurable CORS)
bun run start:optimized

πŸ“‹ Resources

The API provides the same 6 resources as JSONPlaceholder:

  • Posts: 100 posts
  • Comments: 500 comments (5 per post)
  • Albums: 100 albums (10 per user)
  • Photos: 5000 photos (50 per album)
  • Todos: 200 todos (20 per user)
  • Users: 10 users

πŸ“– API Endpoints

Users

GET    /users              # Get all users
GET    /users/1            # Get user by id
GET    /users/1/posts      # Get posts by user
GET    /users/1/albums     # Get albums by user
GET    /users/1/todos      # Get todos by user
POST   /users              # Create new user
PUT    /users/1            # Update user (full replace)
PATCH  /users/1            # Update user (partial)
DELETE /users/1            # Delete user

Posts

GET    /posts              # Get all posts
GET    /posts?userId=1     # Get posts by user
GET    /posts/1            # Get post by id
GET    /posts/1/comments   # Get comments for post
POST   /posts              # Create new post
PUT    /posts/1            # Update post (full replace)
PATCH  /posts/1            # Update post (partial)
DELETE /posts/1            # Delete post

Comments

GET    /comments           # Get all comments
GET    /comments?postId=1  # Get comments by post
GET    /comments/1         # Get comment by id
POST   /comments           # Create new comment
PUT    /comments/1         # Update comment (full replace)
PATCH  /comments/1         # Update comment (partial)
DELETE /comments/1         # Delete comment

Albums

GET    /albums             # Get all albums
GET    /albums?userId=1    # Get albums by user
GET    /albums/1           # Get album by id
GET    /albums/1/photos    # Get photos for album
POST   /albums             # Create new album
PUT    /albums/1           # Update album (full replace)
PATCH  /albums/1           # Update album (partial)
DELETE /albums/1           # Delete album

Photos

GET    /photos             # Get all photos
GET    /photos?albumId=1   # Get photos by album
GET    /photos/1           # Get photo by id
POST   /photos             # Create new photo
PUT    /photos/1           # Update photo (full replace)
PATCH  /photos/1           # Update photo (partial)
DELETE /photos/1           # Delete photo

Todos

GET    /todos              # Get all todos
GET    /todos?userId=1     # Get todos by user
GET    /todos/1            # Get todo by id
POST   /todos              # Create new todo
PUT    /todos/1            # Update todo (full replace)
PATCH  /todos/1            # Update todo (partial)
DELETE /todos/1            # Delete todo

Admin

POST   /reset              # Reset all data to initial state (only when ENABLE_UPDATES=1)

πŸ“¦ Postman Collection

A comprehensive Postman collection is available to test all API endpoints easily:

Import Collection

  1. Download the collection file: collections/JSONPlaceholder.postman_collection.json
  2. Open Postman
  3. Click Import > Upload Files
  4. Select the collection file
  5. The collection will be imported with all endpoints ready to use

Collection Features

  • βœ… Complete CRUD Operations - GET, POST, PUT, PATCH, DELETE for all resources
  • βœ… Query Parameter Examples - Filtering by userId, postId, albumId
  • βœ… Environment Variable - {{baseUrl}} set to http://localhost:3000
  • βœ… Sample Request Bodies - Pre-filled JSON data for testing
  • βœ… Organized Structure - Grouped by resource type (Users, Posts, Comments, etc.)
  • βœ… Admin Endpoints - Reset functionality when ENABLE_UPDATES=1

Collection Structure

  • πŸ“ Posts - Full CRUD + filtering by user
  • πŸ“ Users - Full CRUD operations
  • πŸ“ Comments - Full CRUD + filtering by post
  • πŸ“ Albums - Full CRUD + filtering by user
  • πŸ“ Photos - Full CRUD + filtering by album
  • πŸ“ Todos - Full CRUD + filtering by user
  • πŸ“ Admin - Reset data endpoint

Usage Tips

  1. Start the server first: bun run start
  2. Import the collection into Postman
  3. Test basic endpoints like "Get All Users" or "Get All Posts"
  4. Try CRUD operations - Create, Update, Patch, Delete
  5. Use query parameters to filter data by relationships
  6. Reset data using the Admin endpoint when needed

πŸ§ͺ Example Usage

JavaScript/Fetch

// Get all posts
fetch("http://localhost:3000/posts")
  .then((response) => response.json())
  .then((posts) => console.log(posts));

// Get specific post
fetch("http://localhost:3000/posts/1")
  .then((response) => response.json())
  .then((post) => console.log(post));

// Create new post
fetch("http://localhost:3000/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "My New Post",
    body: "This is the content of my new post",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((newPost) => console.log(newPost));

cURL

# Get all users
curl http://localhost:3000/users

# Get specific user
curl http://localhost:3000/users/1

# Create new todo
curl -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{"title":"Learn Bun","completed":false,"userId":1}'

# Update existing todo
curl -X PATCH http://localhost:3000/todos/1 \
  -H "Content-Type: application/json" \
  -d '{"completed":true}'

πŸ—οΈ Data Structure

User

{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "[email protected]",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031",
  "website": "bret.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}

Post

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Comment

{
  "postId": 1,
  "id": 1,
  "name": "id labore ex et quam laborum",
  "email": "[email protected]",
  "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
}

Album

{
  "userId": 1,
  "id": 1,
  "title": "quidem molestiae enim"
}

Photo

{
  "albumId": 1,
  "id": 1,
  "title": "accusamus beatae ad facilis cum similique qui sunt",
  "url": "https://via.placeholder.com/600/92c952",
  "thumbnailUrl": "https://via.placeholder.com/150/92c952"
}

Todo

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

🎯 Use Cases

  • Frontend Development: Test your React, Vue, Angular, or vanilla JavaScript applications
  • API Learning: Learn how to consume REST APIs
  • Prototyping: Quick backend for demos and mockups
  • Testing: Unit and integration testing with predictable data
  • Tutorials: Teaching REST API concepts
  • Code Examples: Documentation and Stack Overflow answers

πŸ”§ Development

Prerequisites

  • Bun installed on your system

Setup

# Clone the repository
git clone <your-repo-url>
cd jsonplaceholder.dev

# Install dependencies
bun install

# Start development server
bun run index.ts

Scripts

{
  "scripts": {
    "start": "bun run index.ts",
    "dev": "bun --watch index.ts",
    "start:opt": "bun run index-optimized.ts",
    "dev:opt": "bun --watch index-optimized.ts"
  }
}

πŸ“ Notes

  • Data Persistence: All data is stored in memory and will reset when the server restarts
  • CORS: Enabled for all origins to support frontend development
  • Error Handling: Proper error responses for invalid requests
  • Performance: Optimized for speed with Bun's native performance
  • Compatibility: Drop-in replacement for JSONPlaceholder URLs

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

MIT License - feel free to use this project for any purpose.


Made with ❀️ using Bun + Elysia.js

About

A super fast fake REST API powered by Bun + Elysia.js

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published