{"id":13657374,"url":"https://github.com/muratcorlu/connect-api-mocker","last_synced_at":"2025-05-16T17:06:08.013Z","repository":{"id":8726388,"uuid":"59480018","full_name":"muratcorlu/connect-api-mocker","owner":"muratcorlu","description":"Connect middleware that creates mocks for REST APIs","archived":false,"fork":false,"pushed_at":"2024-06-20T05:21:38.000Z","size":974,"stargazers_count":270,"open_issues_count":10,"forks_count":21,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-12T15:58:27.852Z","etag":null,"topics":["api-mock","connect-middlewares","express-middleware","gruntjs","webpack"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/muratcorlu.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-05-23T12:16:24.000Z","updated_at":"2025-03-13T00:01:03.000Z","dependencies_parsed_at":"2024-06-18T13:47:46.095Z","dependency_job_id":"c15111dc-6896-47bc-a453-75839bcc8e2a","html_url":"https://github.com/muratcorlu/connect-api-mocker","commit_stats":{"total_commits":113,"total_committers":21,"mean_commits":5.380952380952381,"dds":0.6725663716814159,"last_synced_commit":"71beb6c785d147d63b6897f3acfb326b5b3a05ac"},"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muratcorlu%2Fconnect-api-mocker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muratcorlu%2Fconnect-api-mocker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muratcorlu%2Fconnect-api-mocker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muratcorlu%2Fconnect-api-mocker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/muratcorlu","download_url":"https://codeload.github.com/muratcorlu/connect-api-mocker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254573588,"owners_count":22093731,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-mock","connect-middlewares","express-middleware","gruntjs","webpack"],"created_at":"2024-08-02T05:00:41.687Z","updated_at":"2025-05-16T17:06:07.960Z","avatar_url":"https://github.com/muratcorlu.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"connect-api-mocker\n==================\n\n[![Build Status](https://travis-ci.org/muratcorlu/connect-api-mocker.svg?branch=master)](https://travis-ci.org/muratcorlu/connect-api-mocker) [![npm version](https://badge.fury.io/js/connect-api-mocker.svg)](https://www.npmjs.com/package/connect-api-mocker) [![codecov](https://codecov.io/gh/muratcorlu/connect-api-mocker/branch/master/graph/badge.svg)](https://codecov.io/gh/muratcorlu/connect-api-mocker) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n\n`connect-api-mocker` is a [connect.js](https://github.com/senchalabs/connect) middleware that fakes REST API server with filesystem. It will be helpful when you try to test your application without the actual REST API server.\n\nIt works with a wide range of servers: [connect][], [express][], [browser-sync][], [lite-server][], [webpack-dev-server][]. Also it can be used as a command line tool with the help of [cli-api-mocker](https://github.com/muratcorlu/cli-api-mocker).\n\nDetailed article: [https://medium.com/@muratcorlu/mocking-rest-endpoints-in-web-apps-easy-way-d4cd0e9db000](https://medium.com/@muratcorlu/mocking-rest-endpoints-in-web-apps-easy-way-d4cd0e9db000)\n\nA presentation at AmsterdamJS'18 conference: [https://www.youtube.com/watch?v=yF_8O4l-Ybc](https://www.youtube.com/watch?v=yF_8O4l-Ybc)\n\nTürkçe sunum için: https://www.youtube.com/watch?v=cVL8sesauCU\n\n## Installation\n\n```\nnpm install connect-api-mocker --save-dev\n```\n\n## Usage\n\n### Using with [Connect][]\n\n```js\nvar http = require('http');\nvar connect = require('connect');\nvar apiMocker = require('connect-api-mocker');\n\nvar app = connect();\n\napp.use('/api', apiMocker('mocks/api'));\n\nhttp.createServer(app).listen(8080);\n```\n\n### Using with [Express][]\n\n```js\nvar express = require('express');\nvar apiMocker = require('connect-api-mocker');\n\nvar app = express();\n\napp.use('/api', apiMocker('mocks/api'));\n\napp.listen(8080);\n```\n\n### Using with [BrowserSync][]\n\n```js\nvar browserSync = require('browser-sync').create();\nvar apiMocker = require('connect-api-mocker');\n\nvar restMock = apiMocker('/api', 'mocks/api');\n\nbrowserSync.init({\n  server: {\n    baseDir: './',\n    middleware: [\n      restMock,\n    ],\n  },\n  port: 8080,\n});\n```\n\n### Using with [lite-server][]\n\n`bs-config.js` file:\n\n```js\nvar apiMocker = require('connect-api-mocker');\n\nvar restMock = apiMocker('/api', 'mocks/api');\n\nmodule.exports = {\n  server: {\n    middleware: {\n      // Start from key `10` in order to NOT overwrite the default 2 middleware provided\n      // by `lite-server` or any future ones that might be added.\n      10: restMock,\n    },\n  },\n  port: 8080,\n};\n```\n\n### Using with Grunt\n\nYou can use it with [Grunt](http://gruntjs.com). After you install [grunt-contrib-connect](https://github.com/gruntjs/grunt-contrib-connect) add api-mocker middleware to your grunt config. The `mocks/api` folder will be served as REST API at `/api`.\n\n```js\n\nmodule.exports = function(grunt) {\n  var apiMocker = require('connect-api-mocker');\n\n  grunt.loadNpmTasks('grunt-contrib-connect');  // Connect - Development server\n\n  // Project configuration.\n  grunt.initConfig({\n\n    // Development server\n    connect: {\n      server: {\n        options: {\n          base: './build',\n          port: 9001,\n          middleware: function(connect, options) {\n\n            var middlewares = [];\n\n            // mock/rest directory will be mapped to your fake REST API\n            middlewares.push(apiMocker(\n                '/api',\n                'mocks/api'\n            ));\n\n            // Static files\n            middlewares.push(connect.static(options.base));\n            middlewares.push(connect.static(__dirname));\n\n            return middlewares;\n          }\n        }\n      }\n    }\n  });\n}\n```\n\nAfter you can run your server with `grunt connect` command. You will see `/api` will be mapped to `mocks/api`.\n\n### Using with Webpack\n\nTo use api mocker on your [Webpack][] projects, simply add a setup options to your [webpack-dev-server][] options:\n\n\u003e [devServer.setup](https://doc.webpack-china.org/configuration/dev-server/#devserver-setup) , This option is deprecated in favor of before and will be removed in v3.0.0.\n\n```js\n  ...\n  before: function(app) {\n    app.use(apiMocker('/api', 'mocks/api'));\n  },\n  ...\n```\n### Using with CRA\n\nTo use api mocker on your [cra][] projects, please install [customize-cra] and [react-app-rewired] using npm to modify webpack config file:\n```\nnpm install customize-cra react-app-rewired --save-dev\n```\nThen, create a file named config-overrides.js, override webpack config using below codes:\n\n```js\n  const apiMocker = require(\"connect-api-mocker\"),\n    { overrideDevServer } = require(\"customize-cra\");\n\n  const devServerConfig = () =\u003e config =\u003e {\n    return {\n        ...config,\n        before: (app,server)=\u003e {\n            //call cra before function to not break code\n            config.before(app, server);\n            //Then add our mocker url and folder \n            app.use(apiMocker('/api', 'mocks/api'));\n        } \n    }\n  }\n\n  module.exports = {\n    devServer: overrideDevServer(\n      devServerConfig()\n    )\n  };\n```\nFinally, change our run method to from \"react-scripts start\" to \"react-app-rewired start\" in package.json file:\n```js\n...\n\"scripts\": {\n    \"start\": \"react-app-rewired start\",\n    ...\n  }\n  ...\n```\n### Using with other languages other than JavaScript\n\nIf you have a Python/Ruby/.NET etc. project and want to use that mocking functionality, you can use [cli-api-mocker](https://github.com/muratcorlu/cli-api-mocker) as a wrapper of connect-api-mocker for command line. With the help of cli-api-mocker, if you run `mockit` command, you will have a seperate web server that will handle your mocks as a REST API. Please look for [cli-api-mocker readme](https://github.com/muratcorlu/cli-api-mocker) for details.\n\n## Directory Structure\n\nYou need to use service names as directory name and http method as filename. Middleware will match url to directory structure and respond with the corresponding http method file.\n\nExample REST service: `GET /api/messages`\n\nDirectory Structure:\n\n```\n_ api\n  \\_ messages\n     \\_ GET.json\n```\n\nExample REST service: `GET /api/messages/1`\n\nDirectory Structure:\n\n```\n_ api\n  \\_ messages\n     \\_ 1\n        \\_ GET.json\n```\n\nExample REST service: `POST /api/messages/1`\n\nDirectory Structure:\n\n```\n_ api\n  \\_ messages\n     \\_ 1\n        \\_ POST.json\n```\n\n\nExample REST service: `DELETE /api/messages/1`\n\nDirectory Structure:\n\n```\n_ api\n  \\_ messages\n     \\_ 1\n        \\_ DELETE.json\n```\n\n## Custom responses\n\nIf you want define custom responses you can use `js` files with a middleware function that handles requests.\n\nExample REST service: `POST /api/messages`\n\nDirectory Structure:\n\n```\n_ api\n  \\_ messages\n     \\_ POST.js\n```\n\n`POST.js` file:\n\n```js\nmodule.exports = function (request, response) {\n  if (!request.get('X-Auth-Key')) {\n    response.status(403).send({});\n  } else {\n    response.sendFile('POST.json', {root: __dirname});\n  }\n}\n```\n\n`POST.js` file for non ExpressJS server:\n\n```js\nconst fs = require('fs');\nconst path = require('path');\n\nmodule.exports = (request, response) =\u003e {\n  if (!request.get('X-Auth-Key')) {\n    response.statusCode = 403;\n    response.end();\n  } else {\n    const filePath = path.join(__dirname, 'POST.json');\n    const stat = fs.statSync(filePath);\n\n    response.writeHead(200, {\n        'Content-Type': 'application/json',\n        'Content-Length': stat.size\n    });\n\n    const readStream = fs.createReadStream(filePath);\n    // We replaced all the event handlers with a simple call to readStream.pipe()\n    readStream.pipe(response);\n  }\n}\n```\n### Another Example: Respond different json files based on a query parameter:\n\n- Request to `/users?type=active` will be responded by `mocks/users/GET_active.json`\n- Request to `/users` will be responded by `mocks/users/GET.json`\n\n`GET.js` file:\n\n```js\nconst fs = require('fs');\nconst path = require('path');\n\nmodule.exports = function (request, response) {\n  let targetFileName = 'GET.json';\n\n  // Check is a type parameter exist\n  if (request.query.type) {\n    // Generate a new targetfilename with that type parameter\n    targetFileName = 'GET_' + request.query.type + '.json';\n  }\n  const filePath = path.join(__dirname, targetFileName);\n  // If file does not exist then respond with 404 header\n  try {\n    fs.accessSync(filePath);\n  }\n  catch (err) {\n    return response.status(404);\n  }\n  // Respond with filePath\n  response.sendFile(filePath);\n}\n```\n`GET.js` file for non ExpressJS server:\n```js\nconst url =  require('url');\nconst fs = require('fs');\nconst path = require('path');\n\nmodule.exports = function (request, response) {\n  let targetFileName = 'GET.json';\n  const typeQueryParam = url.parse(request.url, true).query.type;\n  // Check is a type parameter exist\n  if (typeQueryParam) {\n    // Generate a new targetfilename with that type parameter\n    targetFileName = 'GET_' + typeQueryParam + '.json';\n  }\n\n  var filePath = path.join(__dirname, targetFileName);\n\n  // If file does not exist then respond with 404 header\n  try {\n    fs.accessSync(filePath);\n  }\n  catch (err) {\n    response.statusCode = 404;\n    response.end();\n    return;\n  }\n\n  const stat = fs.statSync(filePath);\n  response.writeHead(200, {\n      'Content-Type': 'application/json',\n      'Content-Length': stat.size\n  });\n\n  const readStream = fs.createReadStream(filePath);\n  // We replaced all the event handlers with a simple call to readStream.pipe()\n  readStream.pipe(response);\n}\n```\n\n## Helper functions for custom responses\n\nConnect-Api-Mocker also presents a bunch of helper functions to speed up writing simple custom responses. There are:\n\n- `status(statusCode)`: Set status code of response\n- `notFound(message?)`: Set status code as 404 and optionally sends message\n- `created()`: Sets status code as 201\n- `success()`: Sets status code as 200\n- `delay(duration)`: Delays the request by given duration(in ms).\n- `json(data|callback(req,res))`: Send given JSON object as response.\n- `file(filePath)`: Responds with the content of file in given path(full path)\n- `type(contentType)`: Sets content-type header.\n- `end(body)`: Ends request and optionally sends the string output\n\nYou can use these functions in custom responses, like:\n\n```js\nconst { notFound } = require('connect-api-mocker/helpers');\n\nmodule.exports = notFound('Page is not found');\n```\n\nAlso you can combine multiple functions:\n\n```js\nconst { delay, created, json } = require('connect-api-mocker/helpers');\n\nmodule.exports = [delay(500), created(), json({success: true})];\n```\n\n`json` middleware also accepts a callback that has request and response objects as parameters:\n\n```js\nconst { json } = require('connect-api-mocker/helpers');\n\nmodule.exports = [json(req =\u003e ({\n  id: req.params.userId,\n  success: true\n}))];\n```\n\nAnother example to return image as response:\n\n```js\nconst { type, file } = require('connect-api-mocker/helpers');\n\n// Assuming a file named GET.png exists next to this file\nconst filePath = path.join(__dirname, './GET.png');\n\nmodule.exports = [type('image/png'), file(filePath)];\n```\n\n## Wildcards in requests\n\nYou can use wildcards for paths to handle multiple urls(like for IDs). If you create a folder structure like `api/users/__user_id__/GET.js`, all requests like `/api/users/321` or `/api/users/1` will be responded by custom middleware that defined in your `GET.js`. Also id part of the path will be passed as a request parameter named as `user_id` to your middleware. So you can write a middleware like that:\n\n`api/users/__user_id__/GET.js` file:\n\n```js\nmodule.exports = function (request, response) {\n  response.json({\n    id: request.params.user_id\n  });\n}\n```\n\nYou can also define `ANY.js` or `ANY.json` files that catch all methods.\n\n`api/users/__user_id__/ANY.js` file:\n\n```js\nmodule.exports = function (request, response) {\n  response.json({\n    id: request.params.user_id,\n    method: request.method\n  });\n}\n```\n\n## XML Support\n\nApi Mocker also can handle XML responses. As you can see, for custom responses, it's not an issue. Because you are completely free about responses in custom responses. But for simple mocks, api mocker try to find a json file by default. You can set that behaviour as `type` in api mocker configuration:\n\n```js\napp.use('/user-api', apiMocker({\n  target: 'other/target/path',\n  type: 'xml'\n}));\n```\n\nIf you use `xml` as type, api mocker should look for `mocks/users/GET.xml` file for a request to `/users`. Also you can use `auto` for type:\n\n```js\napp.use('/user-api', apiMocker({\n  target: 'other/target/path',\n  type: 'auto'\n}));\n```\n\nIn that case, api mocker will look for `Accept` header in the request to determine response format. So, if you make a request with a `Accept: application/json` header, it'll try to send a response with a `json` file. If you make a request with a `Accept: application/xml` header, it'll try to send a response with an `xml` file.\n\n## Defining multiple mock configurations\n\nYou can use apiMocker multiple times with your connect middleware server. In example below, we are defining 3 mock server for 3 different root paths:\n\n```js\napp.use('/api/v1', apiMocker('target/path'));\napp.use('/user-api', apiMocker({\n  target: 'other/target/path'\n}));\napp.use(apiMocker('/mobile/api', {\n  target: 'mocks/mobile'\n});\n```\n\n## Next on not found option\n\nIf you have some other middlewares that handles same url(a real server proxy etc.) you can set `nextOnNotFound` option to `true`. In that case, api mocker doesnt trigger a `404` error and pass request to next middleware. (default is `false`)\n\n```js\napiMocker('/api', {\n  target: 'mocks/api',\n  nextOnNotFound: true\n});\n```\n\nWith that option, you can mock only specific urls simply.\n\n## Body parser\n\nBy default request body is pre-processed with [body-parser](https://github.com/expressjs/body-parser). Default body-parser configuration uses JSON parser. Example belows configures usage of `json` (default) parser. In order to disable default pre-processing set `bodyParser` option to `false`.\n\n```js\napiMocker('/text', {\n  target: 'test/mocks',\n  bodyParser: false\n})\n```\n\nIn order to modify default body-parser behaviour use `bodyParser` object.\n`bodyParser` object supports configuration of\n\n - parser type via `type` setting. \n - parser options via `options` setting.\n\nSupported parsers and corresponding options can be found [here](https://github.com/expressjs/body-parser#bodyparserjsonoptions)\n\nExample belows configures usage of `text` parser for requests with `content-type=application/vnd.custom-type`\n```js\napiMocker('/text', {\n  target: 'test/mocks',\n  bodyParser: {\n    type: 'text',\n    options: { type: 'application/vnd.custom-type' }\n  }\n})\n```\n\n## Logging\n\nIf you want to see which requests are being mocked, set the `verbose` option either to `true` or provide your own function.\n\n```js\napiMocker('/api', {\n  target: 'mocks/api',\n  verbose: ({ req, filePath, fileType }) =\u003e console.log(`Mocking endpoint ${req.originalUrl} using ${filePath}.${fileType}.`)\n});\n```\n\n\u003c!-- Definitions --\u003e\n\n[connect]: https://github.com/senchalabs/connect\n[express]: https://github.com/expressjs/express\n[browsersync]: https://github.com/BrowserSync/browser-sync\n[browser-sync]: https://github.com/BrowserSync/browser-sync\n[lite-server]: https://github.com/johnpapa/lite-server\n[webpack]: https://github.com/webpack/webpack\n[webpack-dev-server]: https://github.com/webpack/webpack-dev-server\n[cra]: https://github.com/facebook/create-react-app\n[customize-cra]: https://github.com/arackaf/customize-cra\n[react-app-rewired]: https://github.com/timarney/react-app-rewired\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmuratcorlu%2Fconnect-api-mocker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmuratcorlu%2Fconnect-api-mocker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmuratcorlu%2Fconnect-api-mocker/lists"}