Skip to content

How to prototype a REST API

Lloyd Brookes edited this page Jul 6, 2021 · 3 revisions

This documentation is a WIP

  1. Install dependencies
$ npm install --save-dev lws lws-body-parser koa-route
  1. Create this middleware module, save it as users.js.
const users = [
  { id: 1, name: 'Lloyd', age: 43 },
  { id: 2, name: 'Mona', age: 34 },
  { id: 3, name: 'Francesco', age: 24 }
]

class Users {
  middleware () {
    const router = require('koa-route')
    return [
      router.get('/users', function (ctx) {
        ctx.response.type = 'json'
        ctx.response.body = users
      }),
      router.put('/users', function (ctx) {
        ctx.response.status = 405
      }),
      router.delete('/users', function (ctx) {
        ctx.response.status = 405
      }),
      router.post('/users', function (ctx) {
        const newUser = ctx.request.body
        users.push(newUser)
        newUser.id = users.length
        ctx.response.status = 201
        ctx.response.set('Location', `/users/${newUser.id}`)
      }),
      router.get('/users/:id', function (ctx, id) {
        ctx.response.type = 'json'
        ctx.response.body = users.find(user => user.id === Number(id))
      }),
      router.put('/users/:id', function (ctx, id) {
        const existingUserIndex = users.findIndex(user => user.id === Number(id))
        const existingUser = users.find(user => user.id === Number(id))
        const updatedUser = Object.assign({}, existingUser, ctx.request.body)
        users.splice(existingUserIndex, 1, updatedUser)
        ctx.response.status = 204
      }),
      router.delete('/users/:id', function (ctx, id) {
        const existingUserIndex = users.findIndex(user => user.id === Number(id))
        users.splice(existingUserIndex, 1)
        ctx.response.status = 204
      }),
      router.post('/users/:id', function (ctx) {
        ctx.response.status = 405
      })
    ]
  }
}

export default Users
  1. Launch your REST API.
$ npx lws --stack body-parser users.js
  1. Make requests.
$ curl -i http://localhost:8000/users
$ curl -i -X POST http://127.0.0.1:8000/users -H 'Content-type: application/json' -d '{ "name": "Derick" }'
$ curl -i -X PUT http://127.0.0.1:8000/users/1 -H 'Content-type: application/json' -d '{ "name": "Updated" }'
$ curl -i -X DELETE http://127.0.0.1:8000/users/2
Clone this wiki locally