{"id":18458512,"url":"https://github.com/appgeist/restful-api","last_synced_at":"2025-04-23T15:15:06.612Z","repository":{"id":35020748,"uuid":"197380034","full_name":"appgeist/restful-api","owner":"appgeist","description":"An opinionated, convention-over-configuration Express-based restful API server featuring yup validation","archived":false,"fork":false,"pushed_at":"2022-12-10T22:43:55.000Z","size":368,"stargazers_count":1,"open_issues_count":8,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-23T15:15:02.374Z","etag":null,"topics":["api","api-helper","api-server","nodejs","rest","rest-api","rest-api-framework","rest-api-helper","rest-server","validation","validation-engine","validation-library","yup"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/appgeist.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-07-17T11:55:50.000Z","updated_at":"2020-08-08T16:23:44.000Z","dependencies_parsed_at":"2023-01-15T12:10:13.317Z","dependency_job_id":null,"html_url":"https://github.com/appgeist/restful-api","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/appgeist%2Frestful-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/appgeist%2Frestful-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/appgeist%2Frestful-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/appgeist%2Frestful-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/appgeist","download_url":"https://codeload.github.com/appgeist/restful-api/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250457792,"owners_count":21433734,"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","api-helper","api-server","nodejs","rest","rest-api","rest-api-framework","rest-api-helper","rest-server","validation","validation-engine","validation-library","yup"],"created_at":"2024-11-06T08:18:58.044Z","updated_at":"2025-04-23T15:15:06.595Z","avatar_url":"https://github.com/appgeist.png","language":"JavaScript","readme":"# @appgeist/restful-api\n\n[![NPM version][npm-image]][npm-url]\n[![License][license-image]][license-url]\n\n![AppGeist Restful API](https://user-images.githubusercontent.com/581999/61737471-f5aa8600-ad90-11e9-8059-cff04086f3bd.png)\n\nAn opinionated, [convention-over-configuration](https://en.wikipedia.org/wiki/Convention_over_configuration) [Express](https://expressjs.com)-based restful API server featuring [yup](https://www.npmjs.com/package/yup) validation.\n\n## Usage\n\n### Initialization\n\nYou can use `@appgeist/restful-api` either as an _Express_ middleware:\n\n```js\nconst express = require(\"express\");\nconst api = require(\"@appgeist/restful-api\");\n\nconst [host, port] = [\"0.0.0.0\", 3000];\n\nexpress()\n  // other middleware\n  .use(api())\n  // other middleware\n  .listen(port, host, err =\u003e {\n    if (err) throw err;\n    // eslint-disable-next-line no-console\n    console.log(`Server listening on http://${host}:${port}...`);\n  });\n```\n\n...or directly:\n\n```js\nconst api = require(\"@appgeist/restful-api\");\n\nconst [host, port] = [\"0.0.0.0\", 3000];\n\napi().listen(port, host, err =\u003e {\n  if (err) throw err;\n  // eslint-disable-next-line no-console\n  console.log(`Server listening on http://${host}:${port}...`);\n});\n```\n\nWhen initializing `@appgeist/restful-api` you can optionally specify the folder containing the route handler definitions (defaults to `./routes`):\n\n```js\nconst path = require(\"path\");\nconst api = require(\"@appgeist/restful-api\");\n\nconst [host, port] = [\"0.0.0.0\", 3000];\n\napi(path.join(__dirname, \"api-routes\")).listen(port, host, err =\u003e {\n  if (err) throw err;\n  // eslint-disable-next-line no-console\n  console.log(`Server listening on http://${host}:${port}...`);\n});\n```\n\n### Defining route handlers\n\nName your route handler definition modules `get.js`, `post.js`, `put.js`, `patch.js` or `delete.js` and organize them in a meaningful folder structure that will get translated to rest API routes.\n\nFor instance:\n\n```\nroutes/departments/get.js =\u003e GET /departments\nroutes/departments/post.js =\u003e POST /departments\nroutes/departments/[id]/patch.js =\u003e PATCH /departments/3\nroutes/departments/[id]/delete.js =\u003e DELETE /departments/3\nroutes/departments/[id]/employees/get.js =\u003e GET /departments/3/employees\nroutes/departments/[id]/employees/post.js =\u003e POST /departments/3/employees\nroutes/departments/[id]/employees/[id]/get.js =\u003e GET /departments/3/employees/165\nroutes/departments/[id]/employees/[id]/patch.js =\u003e PATCH /departments/3/employees/165\nroutes/departments/[id]/employees/[id]/delete.js =\u003e DELETE /departments/3/employees/165\n```\n\nEach module exports:\n\n- `beforeRequest` - an optional before request handler function;\n- `onRequest` - a mandatory request handler function;\n- `paramsSchema`, `querySchema`, `bodySchema` - optional schemas to validate the incoming request params, query and body. These can be simple objects (for brevity, in which case they will be converted to _yup_ schemas automatically) or _yup_ schemas (for more complex scenarios, i.e. when you need to specify a `.noUnknown()` modifier).\n\nA function handler accepts an optional object parameter in the form of `{ params, query, body, req }` and must return the data that will be sent back to the client, or a Promise resolving with the data.\n\nFor simple cases when you don't care about validation, you can export just the handler, like so: `module.exports = () =\u003e {/* handle request here... */};`.\n\n### Nested paths\n\nFor nested paths, **ancestor-level parameter names are _magically_ renamed** with the help of [`pluralize.singular`](https://www.npmjs.com/package/pluralize):\n\n`routes/departments/[id]/employees/[id]/get.js -\u003e params: { departmentId, id }`\n`routes/departments/[id]/employees/[id]/projects/[id]/get.js -\u003e params: { departmentId, projectId, id }`\n\n### Default error handling\n\n#### Validation errors\n\nWhen request data validation fails, the client will receive a response with HTTP status code `400`/`BAD_REQUEST` and a JSON body describing the error provided by [`yup.validate(data, { abortEarly: false })`](https://github.com/jquense/yup#mixedvalidatevalue-any-options-object-promiseany-validationerror):\n\n```json\n{\n  \"message\": \"There were 2 validation errors\",\n  \"errors\": [\"body.name is required\", \"body.description is required\"]\n}\n```\n\n#### Throwing errors\n\nIf a function handler throws an `ApiError(httpStatusCode)` (also [exported](lib/ApiError.js) from this package), the client will receive a response with the specified HTTP status code and a JSON body like `{ \"message\": \"Why it failed\" }`.\n\nThe `ApiError` constructor accepts an HTTP status code number or an object structured like `{ status, message }`.\n\nUsing the constructor without parameters will result in a respose with HTTP status code `500` and the following JSON body:\n\n```json\n{\n  \"message\": \"Internal Server Error\"\n}\n```\n\n### Custom error handling\n\nYou can override the default error handling mechanism by providing a custom error handling function like so:\n\n```js\nconst path = require(\"path\");\nconst api = require(\"@appgeist/restful-api\");\n\nconst [host, port] = [\"0.0.0.0\", 3000];\n\napi(path.join(__dirname, \"api-routes\"), {\n  errorHandler: ({ err, res }) =\u003e {\n    res.status(500).send(\"Error\");\n    console.log(err.stack);\n  }\n}).listen(port, host, err =\u003e {\n  if (err) throw err;\n  // eslint-disable-next-line no-console\n  console.log(`Server listening on http://${host}:${port}...`);\n});\n```\n\n## Example\n\n`routes/departments/get.js`:\n\n```js\nconst Department = require(\"models/Department\");\n\n// simple handler, without validation\nmodule.exports = () =\u003e Department.listAll();\n// ...or exports.onRequest = () =\u003e Department.listAll();\n```\n\n`routes/departments/[id]/patch.js`:\n\n```js\nconst { object, number } = require('yup');\nconst { FORBIDDEN } = require('http-status-codes');\nconst { ApiError } = require('@appgeist/rest-api');\nconst Department = require('models/Department');\nconst ACL = require('utils/acl');\nconst Logger = require('utils/logger');\n\n// schema can be a simple object\nexports.paramsSchema = {\n  id: number().positive().integer().required()\n};\n\n// schema can be a yup object\nexports.bodySchema = object({\n  name: string().min(2).max(20).required()\n  description: string().min(2).max(1000).required()\n}).noUnknown();\n\nexports.onRequest = async ({ params: { id }, body, req }) =\u003e {\n  // throwing an ApiError(403) will result in a 403 status code being sent to the client\n  if (!(ACL.isManager(req.userId))) throw new ApiError(FORBIDDEN);\n  const department = await Department.updateById(id, { data: body });\n  await Logger.log(`Department ${id} updated by user ${req.userId}`);\n  return department;\n}\n```\n\n`routes/departments/[id]/employees/[id]/get.js`:\n\n```js\nconst { number } = require('yup');\nconst Department = require('models/Department');\nconst Employee = require('models/Employee');\n\nexports.paramsSchema = {\n  departmentId: number().positive().integer().required()\n  id: number().positive().integer().required()\n};\n\nexports.beforeRequest = ({ url }) =\u003e {\n  console.log(`Preparing to respond to ${url}`);\n};\n\nexports.onRequest = async ({ params: { departmentId, id } }) =\u003e {\n  const employee = await Employee.getById(id);\n  employee.department = await Department.getById(departmentId);\n  return employee;\n}\n```\n\n## License\n\nThe [ISC License](LICENSE).\n\n[npm-image]: https://img.shields.io/npm/v/@appgeist/restful-api.svg?style=flat-square\n[npm-url]: https://www.npmjs.com/package/@appgeist/restful-api\n[license-image]: https://img.shields.io/npm/l/@appgeist/restful-api.svg?style=flat-square\n[license-url]: LICENSE\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fappgeist%2Frestful-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fappgeist%2Frestful-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fappgeist%2Frestful-api/lists"}