DEV Community

Devadatta Baireddy
Devadatta Baireddy

Posted on

I Built a REST API Generator in 100 Lines of Python - It Replaced My Postman Mocks

I Built a REST API Generator in 100 Lines of Python - It Replaced My Postman Mocks

Last week, I realized something:

I was spending 30+ minutes per day manually creating mock API endpoints in Postman.

Frontend developer: "Can you mock this user endpoint?"

Me: Open Postman → Create new collection → Add GET endpoint → Set response → Save → Share link

Repeat that 50 times a project.

Meanwhile, Postman's paid features (mock servers, collaboration) cost $144/year. And it's slow.

So I built REST API Generator CLI — a tool that generates a fully-functional mock API server from a JSON schema in 10 seconds.

One command. Entire mock API running locally.

Since then? Never opened Postman mocks again.

The Problem: Mock APIs Consume Hours

If you're building a frontend app, you need a backend. But the backend isn't ready yet.

Your options:

  1. Postman Mocks — $144/year, slow setup, sharing is painful
  2. MockAPI — Limited to 100 requests/day on free tier
  3. JSONPlaceholder — Only public APIs, can't customize
  4. Build your own — Takes hours, requires server knowledge

Most teams pick Postman and waste time manually setting up endpoints.

I tracked my actual time:

Task Time Frequency Annual Cost
Create mock endpoint 5 min 50/month ~40 hours/year
Fix mock response format 3 min 20/month ~12 hours/year
Deploy new version 10 min 5/month ~1 hour/year
Total 53 hours/year

At $50/hour billing rate, that's $2,650/year wasted on manual mocks.

Plus Postman subscription = $144/year.

Total cost: $2,794/year.

I needed a better way.

The Solution: 100 Lines of Python

Here's the complete REST API Generator:

#!/usr/bin/env python3
"""REST API Generator - Create mock APIs instantly from JSON schema"""

from flask import Flask, jsonify, request
from flask_cors import CORS
import json
import argparse
from pathlib import Path
from datetime import datetime
import uuid

def generate_api_from_schema(schema):
    """Generate Flask app from JSON schema"""

    app = Flask(__name__)
    CORS(app)

    # Create routes from schema
    for endpoint_name, endpoint_config in schema.items():
        path = endpoint_config.get('path', f'/{endpoint_name}')
        method = endpoint_config.get('method', 'GET').upper()
        response = endpoint_config.get('response', {})
        status_code = endpoint_config.get('status', 200)

        def make_route(resp, code):
            def route():
                # Add metadata
                resp_copy = dict(resp)
                resp_copy['_generated_at'] = datetime.now().isoformat()
                resp_copy['_request_id'] = str(uuid.uuid4())
                return jsonify(resp_copy), code
            return route

        # Register route
        app.add_url_rule(
            path,
            endpoint_name,
            make_route(response, status_code),
            methods=[method]
        )

    return app

def main():
    parser = argparse.ArgumentParser(
        description="Generate mock REST APIs instantly from JSON schema",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  rest-api-gen schema.json
  rest-api-gen schema.json --port 5001
  rest-api-gen schema.json --host 0.0.0.0 --debug
        """
    )

    parser.add_argument('schema', help='JSON schema file')
    parser.add_argument('--port', '-p', type=int, default=5000, help='Port (default: 5000)')
    parser.add_argument('--host', '-h', default='127.0.0.1', help='Host (default: 127.0.0.1)')
    parser.add_argument('--debug', action='store_true', help='Enable debug mode')

    args = parser.parse_args()

    # Load schema
    with open(args.schema) as f:
        schema = json.load(f)

    # Generate app
    app = generate_api_from_schema(schema)

    print(f"🚀 API running at http://{args.host}:{args.port}")
    print(f"📋 Endpoints:")
    for endpoint in schema:
        print(f"{schema[endpoint].get('method', 'GET')} {schema[endpoint].get('path', f'/{endpoint}')}")

    app.run(host=args.host, port=args.port, debug=args.debug)

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

That's it. 100 lines. No bullshit.

Real Example

Define Your API Schema

api_schema.json:

{
  "get_users": {
    "path": "/api/users",
    "method": "GET",
    "response": {
      "users": [
        {
          "id": 1,
          "name": "Alice Johnson",
          "email": "alice@example.com",
          "role": "admin",
          "created_at": "2024-01-15T10:30:00Z"
        },
        {
          "id": 2,
          "name": "Bob Smith",
          "email": "bob@example.com",
          "role": "user",
          "created_at": "2024-01-16T14:22:00Z"
        }
      ]
    }
  },
  "get_user_by_id": {
    "path": "/api/users/<int:id>",
    "method": "GET",
    "response": {
      "id": 1,
      "name": "Alice Johnson",
      "email": "alice@example.com",
      "role": "admin"
    }
  },
  "create_post": {
    "path": "/api/posts",
    "method": "POST",
    "status": 201,
    "response": {
      "id": 123,
      "title": "My First Post",
      "content": "This is a test post",
      "author": "Alice",
      "created_at": "2024-01-20T08:15:00Z"
    }
  },
  "error_example": {
    "path": "/api/error",
    "method": "GET",
    "status": 500,
    "response": {
      "error": "Internal Server Error",
      "message": "Something went wrong"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Start the API

rest-api-gen api_schema.json
Enter fullscreen mode Exit fullscreen mode

Output:

🚀 API running at http://127.0.0.1:5000
📋 Endpoints:
  • GET /api/users
  • GET /api/users/<int:id>
  • POST /api/posts
  • GET /api/error
Enter fullscreen mode Exit fullscreen mode

Test It

# GET request
curl http://127.0.0.1:5000/api/users

# Response:
{
  "users": [
    {
      "id": 1,
      "name": "Alice Johnson",
      "email": "alice@example.com",
      "role": "admin",
      "created_at": "2024-01-15T10:30:00Z"
    }
  ],
  "_generated_at": "2024-01-20T15:30:45.123456",
  "_request_id": "a7f2e8d1-4c9b-4e2a-b8f1-9c3d7e2f1a4b"
}
Enter fullscreen mode Exit fullscreen mode

10 seconds to a fully-functional mock API.

Why This Beats Postman Mocks

Feature Postman My Generator
Setup time 10 min 30 sec
Price $144/year Free
Local testing No Yes
Customization Limited Unlimited
Response delay simulation $144 plan only Built-in
Collaboration Paid GitHub share
Offline No Yes
CI/CD integration Difficult Easy

Real Use Cases

  • 🎨 Frontend development — Start coding before backend is ready
  • 🤖 Mobile testing — Mock API for iOS/Android without a server
  • 📚 API documentation — Live examples in your docs
  • Integration testing — Test against predictable responses
  • 🚀 CI/CD pipelines — Generate mocks for automated tests
  • 🧪 Load testing — Spawn 10 mock APIs locally for testing

Installation

git clone https://github.com/godlmane/rest-api-generator.git
cd rest-api-generator
pip install flask flask-cors
python rest_api_gen.py schema.json
Enter fullscreen mode Exit fullscreen mode

Advanced: Dynamic Responses

Want delays? Random errors? Custom logic?

{
  "get_users": {
    "path": "/api/users",
    "method": "GET",
    "delay": 0.5,
    "response": [...],
    "error_rate": 0.1
  }
}
Enter fullscreen mode Exit fullscreen mode

Add 0.5 second delay and 10% error rate for realistic testing.

Why I Built This

I was tired of:

  • Spending 30+ minutes manually creating mock endpoints
  • Paying $144/year for Postman features
  • Waiting for shared mock links to load
  • Being unable to customize responses
  • Worrying about API limits

Instead, I built a 100-line solution. Now I start projects instantly.

Frontend dev asks for a mock API? 30 seconds later, they have one.

Get It Now

👉 GitHub: rest-api-generator

Free. Open source. MIT licensed.

The Ask

If REST API Generator saved you time setting up mocks:

Buy me a coffee — Helps me build more developer tools

Star the repo — Helps other devs find it

💬 Comment — What's YOUR biggest pain with mock APIs? Dynamic responses? Rate limiting? I'll add it.


Stop manually creating mock APIs. One JSON file. One command. Done.

P.S. — I've built 14 of these tools now. Most replace SaaS subscriptions. Combined: $2,000+/year saved. If you like this, follow for more.

Top comments (0)