rest_api_faker 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 API Faker Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,628 @@
1
+ # API Faker
2
+
3
+ > Get a full fake REST API with **zero coding** in **less than 30 seconds** (seriously)
4
+
5
+ Created with โค๏ธ for front-end developers who need a quick back-end for prototyping and mocking.
6
+
7
+ [![CI](https://github.com/hamidmayeli/api-faker/actions/workflows/ci.yml/badge.svg)](https://github.com/hamidmayeli/api-faker/actions/workflows/ci.yml)
8
+ [![Coverage](https://codecov.io/gh/hamidmayeli/api-faker/branch/main/graph/badge.svg)](https://codecov.io/gh/hamidmayeli/api-faker)
9
+ [![Tests](https://img.shields.io/badge/tests-223%20passing-brightgreen)]()
10
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue)]()
11
+ [![License](https://img.shields.io/badge/license-MIT-blue)]()
12
+ [![npm version](https://img.shields.io/npm/v/rest_api_faker.svg)](https://www.npmjs.com/package/rest_api_faker)
13
+
14
+ ## Table of Contents
15
+
16
+ - [Features](#features)
17
+ - [Installation](#installation)
18
+ - [Getting Started](#getting-started)
19
+ - [Usage](#usage)
20
+ - [CLI Options](#cli-options)
21
+ - [Routes](#routes)
22
+ - [Query Parameters](#query-parameters)
23
+ - [Relationships](#relationships)
24
+ - [Configuration](#configuration)
25
+ - [Custom Routes & Middlewares](#custom-routes--middlewares)
26
+ - [Examples](#examples)
27
+ - [Programmatic Usage](#programmatic-usage)
28
+ - [Development](#development)
29
+ - [License](#license)
30
+
31
+ ## Features
32
+
33
+ - โœจ **Zero coding required** - Start with a JSON file
34
+ - ๐Ÿš€ **Quick setup** - Get an API running in < 30 seconds
35
+ - ๐Ÿ”„ **Full REST API** - Complete CRUD operations (GET, POST, PUT, PATCH, DELETE)
36
+ - ๐Ÿ” **Advanced filtering** - Filter by any property, use operators like \_gte, \_lte, \_like
37
+ - ๐Ÿ“Š **Sorting & Pagination** - Sort by multiple fields, paginate with \_page and \_limit
38
+ - ๐Ÿ”— **Relationships** - Embed child resources and expand parent resources
39
+ - ๐Ÿ“ **Static file serving** - Serve your HTML, CSS, and JS files
40
+ - ๐ŸŽจ **URL rewriting** - Create custom routes and aliases
41
+ - ๐Ÿ”ง **Highly customizable** - CLI options and config file support
42
+ - ๐Ÿ’พ **Auto-save** - Changes are automatically saved to your data file
43
+ - ๐ŸŒ **CORS enabled** - Ready for cross-origin requests
44
+ - โšก **Fast & lightweight** - Built with Express and TypeScript
45
+ - ๐Ÿงช **Well tested** - 214 tests with comprehensive coverage
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ # NPM
51
+ npm install -g rest_api_faker
52
+
53
+ # Yarn
54
+ yarn global add rest_api_faker
55
+
56
+ # PNPM
57
+ pnpm add -g rest_api_faker
58
+ ```
59
+
60
+ ## Getting Started
61
+
62
+ **1. Create a `db.json` file:**
63
+
64
+ ```json
65
+ {
66
+ "posts": [
67
+ { "id": 1, "title": "Hello World", "author": "John Doe" },
68
+ { "id": 2, "title": "API Faker is awesome", "author": "Jane Smith" }
69
+ ],
70
+ "comments": [
71
+ { "id": 1, "body": "Great post!", "postId": 1 },
72
+ { "id": 2, "body": "Thanks for sharing", "postId": 1 }
73
+ ],
74
+ "profile": {
75
+ "name": "John Doe",
76
+ "email": "john@example.com"
77
+ }
78
+ }
79
+ ```
80
+
81
+ **2. Start the server:**
82
+
83
+ ```bash
84
+ api-faker db.json
85
+ ```
86
+
87
+ Or with watch mode to auto-reload on file changes:
88
+
89
+ ```bash
90
+ api-faker --watch db.json
91
+ ```
92
+
93
+ **3. Access your API:**
94
+
95
+ ```bash
96
+ # Get all posts
97
+ curl http://localhost:3000/posts
98
+
99
+ # Get a single post
100
+ curl http://localhost:3000/posts/1
101
+
102
+ # Get profile
103
+ curl http://localhost:3000/profile
104
+ ```
105
+
106
+ That's it! ๐ŸŽ‰ You now have a fully functional REST API.
107
+
108
+ ## Usage
109
+
110
+ ### CLI Options
111
+
112
+ ```bash
113
+ api-faker [options] <source>
114
+
115
+ Options:
116
+ -c, --config <path> Path to config file (default: "api-faker.json")
117
+ -p, --port <number> Set port (default: 3000)
118
+ -H, --host <string> Set host (default: "localhost")
119
+ -w, --watch Watch file(s) for changes
120
+ -r, --routes <path> Path to routes file (URL rewrite rules)
121
+ -m, --middlewares <path> Path to middleware file
122
+ -s, --static <path> Set static files directory (default: "./public")
123
+ --no-static Disable static file serving
124
+ --ro, --read-only Allow only GET requests
125
+ --nc, --no-cors Disable Cross-Origin Resource Sharing
126
+ --ng, --no-gzip Disable GZIP Content-Encoding
127
+ -S, --snapshots <path> Set snapshots directory (default: ".")
128
+ -d, --delay <ms> Add delay to responses (ms)
129
+ -i, --id <field> Set database id property (default: "id")
130
+ --fks <suffix> Set foreign key suffix (default: "Id")
131
+ -q, --quiet Suppress log messages
132
+ -h, --help Show help
133
+ -v, --version Show version number
134
+
135
+ Examples:
136
+ api-faker db.json Start with db.json
137
+ api-faker --watch db.json Start with auto-reload
138
+ api-faker --port 4000 db.json Start on port 4000
139
+ api-faker file.js Use a JavaScript file
140
+ api-faker --routes routes.json Use custom routes
141
+ ```
142
+
143
+ ### Routes
144
+
145
+ Based on your `db.json`, API Faker automatically creates the following routes:
146
+
147
+ #### Plural Resources
148
+
149
+ ```
150
+ GET /posts # List all posts
151
+ GET /posts/1 # Get post with id=1
152
+ POST /posts # Create a new post
153
+ PUT /posts/1 # Replace post with id=1
154
+ PATCH /posts/1 # Update post with id=1
155
+ DELETE /posts/1 # Delete post with id=1
156
+ ```
157
+
158
+ #### Singular Resources
159
+
160
+ ```
161
+ GET /profile # Get profile
162
+ POST /profile # Create/replace profile
163
+ PUT /profile # Replace profile
164
+ PATCH /profile # Update profile
165
+ ```
166
+
167
+ #### Special Routes
168
+
169
+ ```
170
+ GET /db # Get the full database
171
+ GET / # Homepage (serves index.html or shows available routes)
172
+ ```
173
+
174
+ ### Query Parameters
175
+
176
+ #### Filtering
177
+
178
+ Filter by any property:
179
+
180
+ ```bash
181
+ # Posts with specific title
182
+ GET /posts?title=Hello World
183
+
184
+ # Multiple values (OR)
185
+ GET /posts?id=1&id=2
186
+
187
+ # Deep property access
188
+ GET /posts?author.name=John
189
+ ```
190
+
191
+ #### Pagination
192
+
193
+ ```bash
194
+ # Get page 2 with 10 items per page
195
+ GET /posts?_page=2&_limit=10
196
+
197
+ # Default limit is 10
198
+ GET /posts?_page=1
199
+ ```
200
+
201
+ Returns `Link` header with `first`, `prev`, `next`, and `last` links.
202
+
203
+ #### Sorting
204
+
205
+ ```bash
206
+ # Sort by title (ascending)
207
+ GET /posts?_sort=title
208
+
209
+ # Sort by title (descending)
210
+ GET /posts?_sort=title&_order=desc
211
+
212
+ # Sort by multiple fields
213
+ GET /posts?_sort=author,title&_order=desc,asc
214
+ ```
215
+
216
+ #### Slicing
217
+
218
+ ```bash
219
+ # Get items 20-30
220
+ GET /posts?_start=20&_end=30
221
+
222
+ # Get 10 items starting from 20
223
+ GET /posts?_start=20&_limit=10
224
+ ```
225
+
226
+ Returns `X-Total-Count` header with the total number of items.
227
+
228
+ #### Operators
229
+
230
+ ```bash
231
+ # Greater than or equal
232
+ GET /posts?views_gte=1000
233
+
234
+ # Less than or equal
235
+ GET /posts?views_lte=100
236
+
237
+ # Not equal
238
+ GET /posts?author_ne=John
239
+
240
+ # Like (supports RegExp)
241
+ GET /posts?title_like=server
242
+ ```
243
+
244
+ #### Full-Text Search
245
+
246
+ ```bash
247
+ # Search across all string fields
248
+ GET /posts?q=awesome
249
+ ```
250
+
251
+ ### Relationships
252
+
253
+ #### Embed Children
254
+
255
+ Use `_embed` to include child resources (based on foreign keys):
256
+
257
+ ```bash
258
+ # Get post with embedded comments
259
+ GET /posts/1?_embed=comments
260
+
261
+ # Result:
262
+ {
263
+ "id": 1,
264
+ "title": "Hello World",
265
+ "comments": [
266
+ { "id": 1, "body": "Great post!", "postId": 1 }
267
+ ]
268
+ }
269
+ ```
270
+
271
+ #### Expand Parent
272
+
273
+ Use `_expand` to include parent resource:
274
+
275
+ ```bash
276
+ # Get comment with expanded post
277
+ GET /comments/1?_expand=post
278
+
279
+ # Result:
280
+ {
281
+ "id": 1,
282
+ "body": "Great post!",
283
+ "postId": 1,
284
+ "post": { "id": 1, "title": "Hello World" }
285
+ }
286
+ ```
287
+
288
+ #### Nested Routes
289
+
290
+ ```bash
291
+ # Get all comments for post 1
292
+ GET /posts/1/comments
293
+
294
+ # Create a comment for post 1
295
+ POST /posts/1/comments
296
+ {
297
+ "body": "New comment"
298
+ }
299
+ # postId will be automatically set to 1
300
+ ```
301
+
302
+ ## Configuration
303
+
304
+ You can use a configuration file instead of CLI options. Create an `api-faker.json` file:
305
+
306
+ ```json
307
+ {
308
+ "port": 3000,
309
+ "host": "localhost",
310
+ "watch": true,
311
+ "routes": "routes.json",
312
+ "middlewares": "middleware.js",
313
+ "static": "./public",
314
+ "readOnly": false,
315
+ "noCors": false,
316
+ "noGzip": false,
317
+ "delay": 0,
318
+ "id": "id",
319
+ "foreignKeySuffix": "Id",
320
+ "quiet": false
321
+ }
322
+ ```
323
+
324
+ Then simply run:
325
+
326
+ ```bash
327
+ api-faker db.json
328
+ ```
329
+
330
+ **Using a custom config file:**
331
+
332
+ ```bash
333
+ api-faker db.json --config my-config.json
334
+ ```
335
+
336
+ **Note:** CLI arguments override config file values.
337
+
338
+ ## Custom Routes & Middlewares
339
+
340
+ ### Custom Routes (URL Rewriting)
341
+
342
+ Create a `routes.json` file with URL rewrite rules:
343
+
344
+ ```json
345
+ {
346
+ "/api/*": "/$1",
347
+ "/:resource/:id/show": "/:resource/:id",
348
+ "/posts/:category": "/posts?category=:category",
349
+ "/me": "/profile"
350
+ }
351
+ ```
352
+
353
+ Use it:
354
+
355
+ ```bash
356
+ api-faker db.json --routes routes.json
357
+ ```
358
+
359
+ Now you can access:
360
+
361
+ - `/api/posts` โ†’ `/posts`
362
+ - `/posts/1/show` โ†’ `/posts/1`
363
+ - `/posts/tech` โ†’ `/posts?category=tech`
364
+ - `/me` โ†’ `/profile`
365
+
366
+ ### Custom Middlewares
367
+
368
+ Create a `middleware.js` file:
369
+
370
+ ```javascript
371
+ module.exports = function (req, res, next) {
372
+ // Add custom header
373
+ res.setHeader('X-Custom-API', 'API Faker');
374
+
375
+ // Log request
376
+ console.log(`${req.method} ${req.url}`);
377
+
378
+ // Continue
379
+ next();
380
+ };
381
+ ```
382
+
383
+ Use it:
384
+
385
+ ```bash
386
+ api-faker db.json --middlewares middleware.js
387
+ ```
388
+
389
+ See [examples/README.md](examples/README.md) for more examples.
390
+
391
+ ## Examples
392
+
393
+ ### Basic Usage
394
+
395
+ ```bash
396
+ # Start with default settings
397
+ api-faker db.json
398
+
399
+ # Start with watch mode
400
+ api-faker --watch db.json
401
+
402
+ # Start on a different port
403
+ api-faker --port 4000 db.json
404
+
405
+ # Read-only mode (only GET requests)
406
+ api-faker --read-only db.json
407
+
408
+ # Add delay to all responses (useful for testing loading states)
409
+ api-faker --delay 1000 db.json
410
+ ```
411
+
412
+ ### Using JavaScript for Dynamic Data
413
+
414
+ Create a `db.js` file:
415
+
416
+ ```javascript
417
+ module.exports = function () {
418
+ const data = {
419
+ users: [],
420
+ posts: [],
421
+ };
422
+
423
+ // Generate 100 users
424
+ for (let i = 1; i <= 100; i++) {
425
+ data.users.push({
426
+ id: i,
427
+ name: `User ${i}`,
428
+ email: `user${i}@example.com`,
429
+ });
430
+ }
431
+
432
+ // Generate 500 posts
433
+ for (let i = 1; i <= 500; i++) {
434
+ data.posts.push({
435
+ id: i,
436
+ title: `Post ${i}`,
437
+ userId: Math.ceil(Math.random() * 100),
438
+ });
439
+ }
440
+
441
+ return data;
442
+ };
443
+ ```
444
+
445
+ Start the server:
446
+
447
+ ```bash
448
+ api-faker db.js
449
+ ```
450
+
451
+ **Tip:** Use libraries like [Faker.js](https://fakerjs.dev/) for more realistic data.
452
+
453
+ ### Authentication Example
454
+
455
+ Create an authentication middleware:
456
+
457
+ ```javascript
458
+ // auth-middleware.js
459
+ module.exports = function (req, res, next) {
460
+ // Allow all GET requests
461
+ if (req.method === 'GET') {
462
+ return next();
463
+ }
464
+
465
+ // Check for authorization token
466
+ const token = req.headers.authorization;
467
+
468
+ if (!token || token !== 'Bearer secret-token') {
469
+ return res.status(401).json({
470
+ error: 'Unauthorized',
471
+ message: 'Please provide a valid authorization token',
472
+ });
473
+ }
474
+
475
+ next();
476
+ };
477
+ ```
478
+
479
+ Use it:
480
+
481
+ ```bash
482
+ api-faker db.json --middlewares auth-middleware.js
483
+ ```
484
+
485
+ Now all POST, PUT, PATCH, DELETE requests require the `Authorization: Bearer secret-token` header.
486
+
487
+ ### Deployment
488
+
489
+ **Vercel:**
490
+
491
+ Create a `vercel.json`:
492
+
493
+ ```json
494
+ {
495
+ "version": 2,
496
+ "builds": [
497
+ {
498
+ "src": "server.js",
499
+ "use": "@vercel/node"
500
+ }
501
+ ],
502
+ "routes": [
503
+ {
504
+ "src": "/(.*)",
505
+ "dest": "server.js"
506
+ }
507
+ ]
508
+ }
509
+ ```
510
+
511
+ Create a `server.js`:
512
+
513
+ ```javascript
514
+ const jsonServer = require('api-faker');
515
+ const server = jsonServer.create();
516
+ const router = jsonServer.router('db.json');
517
+ const middlewares = jsonServer.defaults();
518
+
519
+ server.use(middlewares);
520
+ server.use(router);
521
+
522
+ module.exports = server;
523
+ ```
524
+
525
+ Deploy:
526
+
527
+ ```bash
528
+ vercel
529
+ ```
530
+
531
+ **Heroku:**
532
+
533
+ Create a `Procfile`:
534
+
535
+ ```
536
+ web: node server.js
537
+ ```
538
+
539
+ Create a `server.js`:
540
+
541
+ ```javascript
542
+ const jsonServer = require('api-faker');
543
+ const server = jsonServer.create();
544
+ const router = jsonServer.router('db.json');
545
+ const middlewares = jsonServer.defaults();
546
+
547
+ const port = process.env.PORT || 3000;
548
+
549
+ server.use(middlewares);
550
+ server.use(router);
551
+ server.listen(port, () => {
552
+ console.log(`API Faker is running on port ${port}`);
553
+ });
554
+ ```
555
+
556
+ Deploy:
557
+
558
+ ```bash
559
+ git init
560
+ git add .
561
+ git commit -m "Initial commit"
562
+ heroku create
563
+ git push heroku main
564
+ ```
565
+
566
+ ## Programmatic Usage
567
+
568
+ You can also use API Faker programmatically in your Node.js applications:
569
+
570
+ ```javascript
571
+ const jsonServer = require('api-faker');
572
+ const server = jsonServer.create();
573
+ const router = jsonServer.router('db.json');
574
+ const middlewares = jsonServer.defaults();
575
+
576
+ server.use(middlewares);
577
+ server.use(router);
578
+
579
+ server.listen(3000, () => {
580
+ console.log('API Faker is running');
581
+ });
582
+ ```
583
+
584
+ **Note:** Full programmatic API is coming in a future release.
585
+
586
+ ## Development
587
+
588
+ ```bash
589
+ # Install dependencies
590
+ pnpm install
591
+
592
+ # Run in development mode
593
+ pnpm dev
594
+
595
+ # Build
596
+ pnpm build
597
+
598
+ # Run tests
599
+ pnpm test
600
+
601
+ # Run tests with coverage
602
+ pnpm test:coverage
603
+
604
+ # Type check
605
+ pnpm typecheck
606
+
607
+ # Lint
608
+ pnpm lint
609
+
610
+ # Format code
611
+ pnpm format
612
+ ```
613
+
614
+ ## Contributing
615
+
616
+ Contributions are welcome! Please feel free to submit a Pull Request.
617
+
618
+ ## License
619
+
620
+ MIT ยฉ 2026
621
+
622
+ ## Acknowledgments
623
+
624
+ Inspired by [json-server](https://github.com/typicode/json-server) by [typicode](https://github.com/typicode).
625
+
626
+ ---
627
+
628
+ **Happy Mocking! ๐Ÿš€**
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../dist/cli.js');
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }