Skip to content

0xdps/api-mockly

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

98 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Mockly Logo

Mockly

Free mock API service for testing and development

A modern, schema-driven alternative to JSONPlaceholder


๐ŸŒ Live: https://mockly.codes
๐Ÿ“š Docs: https://mockly.codes/docs
๐ŸŽฎ Playground: https://mockly.codes/playground

โœจ Features

API Features

  • ๐Ÿš€ Schema-Driven - Add new endpoints by creating JSON schemas (zero code!)
  • ๐ŸŽฏ 100+ Resources - From users to weather, stocks to movies
  • ๐Ÿ“‚ 14 Categories - Resources organized into logical groups (people, commerce, content, etc.)
  • ๐Ÿ’ก Realistic Data - Powered by gofakeit with 50+ generators
  • โšก Blazing Fast - Redis + in-memory cache (<1ms responses)
  • ๐Ÿ”„ Consistent Data - Fixed seed ensures reproducible results
  • ๐Ÿ†“ Free Forever - No rate limits, open source and self-hostable

Advanced Query Features

  • ๐Ÿ“„ Pagination - page, limit, offset parameters
  • ๐Ÿ”€ Sorting - Sort by any field, ascending or descending
  • ๐Ÿ” Search - Full-text search with field targeting
  • ๐ŸŽฏ Filtering - Filter by field values (exact, range, contains)
  • โœ‚๏ธ Field Selection - Return only specific fields

Middleware & Testing

  • โฑ๏ธ Delay Simulation - Test timeouts (max 30s)
  • ๐ŸŽฒ Chaos Engineering - Random failures with flakyRate
  • ๐Ÿšซ Cache Control - Bypass cache for fresh data
  • ๐Ÿข Multi-tenancy - Tenant isolation via X-Tenant-ID
  • ๐Ÿ” RBAC - Role-based testing via X-Role
  • ๐Ÿ”„ Idempotency - Safe retries with Idempotency-Key
  • ๐Ÿ” Request Tracing - Track requests with X-Request-ID

Frontend

  • ๐ŸŽจ Modern UI - Next.js 16 + React 19 with SSR
  • ๐ŸŽฎ Interactive Playground - 50/50 split-screen with tabbed navigation
  • ๐Ÿ“š Comprehensive Docs - Live examples and code snippets
  • ๐Ÿ“Š Cache Management - Admin endpoints for stats
  • ๐Ÿค– Automated Build - TypeScript types auto-generated
  • ๐ŸŒ CORS Enabled - Ready for frontend development

๐Ÿ“ฆ Project Structure

mockly/
โ”œโ”€โ”€ backend/          # Go API service (chi + gofakeit)
โ”‚   โ”œโ”€โ”€ cmd/          # Application entry points
โ”‚   โ”œโ”€โ”€ internal/     # Handlers, middleware, schema
โ”‚   โ”œโ”€โ”€ Dockerfile    # Docker build config
โ”‚   โ””โ”€โ”€ fly.toml      # Fly.io deployment config
โ”œโ”€โ”€ frontend/         # Next.js 16 website (React 19 + TypeScript + Tailwind)
โ”‚   โ”œโ”€โ”€ app/          # Pages (landing, docs, playground)
โ”‚   โ”œโ”€โ”€ components/   # React components
โ”‚   โ””โ”€โ”€ lib/          # Utility functions
โ”œโ”€โ”€ shared/           # Source of truth for schemas & scripts
โ”‚   โ”œโ”€โ”€ schemas/      # Resource definitions (user, post, etc.)
โ”‚   โ””โ”€โ”€ scripts/      # Build scripts (generate-types.js)
โ””โ”€โ”€ package.json      # Root scripts for dev workflow

๐Ÿš€ Quick Start

Development Setup

1. Clone the repository:

git clone https://github.com/0xdps/api-mockly.git
cd api-mockly

2. Install dependencies:

# Install root dependencies (concurrently)
npm install

# Install web dependencies
npm run web:install

3. Start both API and website:

npm run dev

This automatically:

Note: Types are auto-generated on every build. No manual steps needed!

Or run separately:

# API only
npm run api:dev

# Website only  
npm run web:dev

Using the API

Basic Usage:

# Get resources with pagination
curl 'http://localhost:8080/products?page=1&limit=20'

# Get single item
curl http://localhost:8080/products/42

# Get resource metadata
curl http://localhost:8080/products/meta

Advanced Queries:

# Search products
curl 'http://localhost:8080/products?q=laptop&search_fields=name,description'

# Sort products by price
curl 'http://localhost:8080/products?sort=price&order=asc&limit=10'

# Filter by category and price
curl 'http://localhost:8080/products?category=Electronics&price<1000'

# Select specific fields
curl 'http://localhost:8080/products?fields=id,name,price&limit=50'

Testing with Middleware:

# Add 2-second delay
curl 'http://localhost:8080/products?delay=2000'

# Test with 50% failure rate
curl 'http://localhost:8080/products?flakyRate=0.5'

# Bypass cache for fresh data
curl 'http://localhost:8080/products?skip_cache=true'

# Multi-tenant request
curl -H "X-Tenant-ID: tenant-123" http://localhost:8080/products

Production API:

curl 'https://api.mockly.codes/products?page=1&limit=20'

๐Ÿ“š Full API Documentation: backend/API_DOCUMENTATION.md

๐Ÿ“š Available Resources (100 Endpoints!)

๐Ÿ“‚ Resource Groups

Resources are organized into 14 logical categories:

Group Count Resources Description
๐Ÿ›’ Commerce 14 products, orders, payments, coupons, categories, tags, carts, wishlists, promotions, discounts, returns, refunds, shipping, inventory E-commerce
๐Ÿ’ผ Business 12 companies, organizations, jobs, meetings, invoices, subscriptions, clients, contracts, proposals, departments, vendors, reports Business entities
โœˆ๏ธ Travel 10 hotels, flights, restaurants, properties, cars, tours, attractions, bookings, destinations, travelguides Travel & hospitality
๐Ÿ‘ฅ People 10 users, contacts, students, players, employees, customers, profiles, authors, instructors, mentors User profiles and people
๐ŸŽฌ Media 10 movies, books, albums, videos, images, songs, playlists, photos, audios, streams Entertainment media
๐Ÿ’ฌ Social 9 comments, reviews, messages, notifications, testimonials, likes, shares, followers, mentions Social interactions
๐Ÿ“ Content 8 articles, posts, news, podcasts, blogs, tutorials, guides, documents Written content
โœ… Productivity 6 todos, notes, projects, tasks, tickets, events Task management
๐ŸŒ Location 6 countries, cities, weather, states, regions, coordinates Geographic data
๐Ÿ’ฐ Finance 6 currencies, stocks, crypto, transactions, accounts, budgets Financial data
๐Ÿ“š Reference 3 faqs, quotes, languages Reference data
๐Ÿ” Food 3 recipes, ingredients, dishes Food & cooking
โšฝ Sports 2 matches, teams Sports data
๐ŸŽ“ Education 1 courses Educational content

API Endpoints

Group Endpoints:

GET /{group}                    # Group info (metadata only)
GET /{group}/{resource}         # Collection via group path
GET /{group}/{resource}/:id     # Single item via group path

Direct Resource Endpoints:

GET /{resource}?count=N         # Collection (max 100)
GET /{resource}/:id             # Single item
GET /{resource}/meta            # Resource metadata

Examples:

# Browse by category
curl https://api.mockly.codes/people
# Returns: {"group": "people", "resources": ["users", "contacts", ...], "count": 4}

# Get data via category path
curl 'https://api.mockly.codes/people/users?count=5'

# Or access directly (backwards compatible)
curl 'https://api.mockly.codes/users?count=5'

Production API: https://api.mockly.codes

๐ŸŽฏ Schema-Driven Development

Adding a New Resource (Zero Code!)

1. Create a schema in shared/schemas/:

Note: TypeScript types are automatically generated from schemas during build. No manual steps required!

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Order",
  "type": "object",
  "x-resource": {
    "name": "orders",
    "singular": "order",
    "description": "E-commerce orders",
    "group": "commerce",
    "routes": {
      "path": "/orders",
      "methods": ["GET"],
      "aliases": ["/purchases"]
    }
  },
  "properties": {
    "id": {
      "type": "integer",
      "x-generator": "random_int",
      "x-generator-params": { "min": 1, "max": 10000 }
    },
    "total": {
      "type": "number",
      "x-generator": "random_int",
      "x-generator-params": { "min": 10, "max": 500 }
    },
    "status": {
      "type": "string",
      "x-generator": "word"
    }
  }
}

2. Restart the API server:

cd backend && make dev
# or: go run cmd/server/main.go

That's it! Your new endpoint is live at /orders ๐ŸŽ‰

The build process automatically:

  • โœ… Syncs schemas to backend
  • โœ… Generates TypeScript types for frontend
  • โœ… Loads new routes in API server

See BUILD_PROCESS.md for details.

Custom Routes

Define custom paths, aliases, and methods in schemas:

{
  "x-resource": {
    "name": "todos",
    "routes": {
      "path": "/todos",
      "aliases": ["/tasks", "/todo-items"],
      "methods": ["GET", "POST"]
    }
  }
}

This creates:

  • โœ… GET /todos
  • โœ… GET /tasks (alias)
  • โœ… GET /todo-items (alias)

Supported Generators (200+)

We support over 200 generators via gofakeit. Popular ones:

Personal: name, first_name, email, username, password, avatar
Address: address, city, country, zip_code, latitude, longitude
Company: company, job, catch_phrase, company_name, job_title
Internet: url, domain_name, ipv4, uuid, mac_address, image_url
Dates: date, date_time, past_date, future_date, time_zone
Text: word, sentence, paragraph, text, quote_text
Numbers: random_int, random_digit, random_number, float32
Weather: weather_temperature, weather_description, weather_humidity
Finance: currency_code, exchange_rate, stock_symbol, crypto_name
Geography: country_name, city_name, language_name, capital_city
Media: movie_title, book_title, album_title, video_title
Travel: flight_number, hotel_name, restaurant_name, recipe_name
Business: invoice_number, order_id, payment_status, ticket_id
Other: phone_number, boolean, user_agent, car_model

See all generators in backend/internal/schema/loader.go

โšก Cache & Performance

The backend uses an in-memory cache with warmup on startup for blazing fast responses:

๐Ÿ”ฅ Starting cache warmup (seed: 42, items per resource: 100)...
โœ… Cache warmup completed in 2.5s
   ๐Ÿ“Š Resources: 100, Total items: 10,000

Benefits

  • <1ms response times - Pre-generated data served from memory
  • Consistent data - Same ID always returns same object (perfect for testing)
  • Reproducible - Fixed seed (42) ensures same data across restarts
  • Low CPU usage - Generate once, serve thousands of times

Configuration

Configure via environment variables:

# Number of items to cache per resource (default: 100)
CACHE_ITEMS_PER_RESOURCE=100

# Random seed for reproducible data (default: 42)
CACHE_SEED=42

Admin Endpoints

# View cache statistics
GET /admin/cache/stats

# Refresh cache (regenerate all data)
POST /admin/cache/refresh

Cache Bypass

Get fresh data without using cache (useful for testing/demos):

# Via query parameter
GET /users?nocache=true
GET /products?fresh=true

# Via header
curl -H "X-No-Cache: true" http://localhost:8080/users
curl -H "Cache-Control: no-cache" http://localhost:8080/products

All responses include X-Cache header:

  • X-Cache: HIT - Served from cache
  • X-Cache: BYPASS - Cache bypassed
  • X-Cache: MISS - Cache miss

๐Ÿ“– Full cache documentation: backend/CACHE.md
๐Ÿ“– Cache bypass guide: backend/CACHE_BYPASS.md

๐Ÿš€ Deployment

Quick Deploy

Backend (Fly.io):

cd backend
make deploy  # Auto-syncs schemas and deploys

Frontend (Vercel):

cd frontend
vercel --prod  # Auto-generates types and deploys

Important: Schema Syncing

The deployment process automatically includes all schemas:

  • โœ… Backend: Schemas copied from shared/ during Docker build
  • โœ… Frontend: Types auto-generated via prebuild hook
  • โœ… No manual steps required!

See DEPLOYMENT.md for complete deployment guide.

Production URLs

๐Ÿ› ๏ธ Technology Stack

Backend (API)

  • Language: Go 1.23+
  • Router: chi v5 (lightweight, idiomatic)
  • Data Generation: gofakeit/v7
  • CORS: go-chi/cors
  • Deployment: Fly.io

Frontend (Website)

  • Framework: Next.js 16 (App Router with SSR)
  • Language: TypeScript
  • UI Library: React 19
  • Styling: Tailwind CSS
  • HTTP Client: pingpong-fetch (universal, fast, type-safe)
  • Rendering: Server-Side with ISR (5-minute cache)
  • Deployment: Vercel
  • API Integration: https://api.mockly.codes

๐Ÿ“– Documentation

API Documentation

Comprehensive API Reference: backend/API_DOCUMENTATION.md

  • ๐Ÿ“‹ Complete endpoint reference
  • ๐Ÿ” All query parameters (pagination, sorting, search, filtering)
  • ๐Ÿ› ๏ธ All 11 middleware features documented
  • ๐Ÿ’ป Code examples (JavaScript, Python, cURL)
  • ๐Ÿ“Š Response formats and error handling
  • โœจ Best practices and advanced usage

Online Documentation: Visit https://mockly.codes/docs for:

  • Quick start guide (4 languages)
  • Interactive schema explorer
  • Live "Try It" buttons
  • Real-time API status

Interactive Playground

Visit https://mockly.codes/playground to:

  • ๐ŸŽฎ Test all API features
  • ๐Ÿ“„ Pagination, sorting, search controls
  • ๐Ÿ› ๏ธ Middleware testing (delay, flaky, cache)
  • ๐Ÿ” Request/response inspection
  • ๐Ÿ“‹ Copy code examples
  • 5 utility tools: Echo, Status, Delay, Middleware, Chaos

๐Ÿค Contributing

Contributions welcome! The easiest way to contribute is to add new resource schemas:

  1. Create shared/schemas/your-resource.json
  2. Test locally with npm run dev (types auto-generate!)
  3. Submit a PR

See CONTRIBUTING.md for detailed guidelines.

๐Ÿ“š Documentation

๏ฟฝ License

MIT License - see LICENSE

๐Ÿ™ Acknowledgments

Built with:


Made with โค๏ธ by Devendra Pratap

About

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •