My First REST API » Add a New User

My First REST API » Add a New User

Add a New User

Let's look at another small evolution of our REST API. Now it's time to get some real data from the user and modify our small database.

Setup Route & Schema

I usually start by scaffolding the route's handler. I don't implement any logic, but I strongly suggest you to implement the route's schema definition so to add some safety to your internal logic.

Start with /users/routes/add-user.js:

const handler = (request, reply) => {
  // Logic will go here

const schema = {
  query: {
    type: 'object',
    properties: {
      name: { type: 'string' },
    additionalProperties: false,
    required: ['name'],

module.exports = { handler, schema };

Then in /users/index.js we can simply add a new route's definition to the list that we have already prepared:

  method: "GET",
  url: "/users/add",
  schema: addUser.schema,
  handler: addUser.handler

💻 Live on CodeSandbox:

Modify the App's Context

The implementation of our handler is still very simplicistic, but again we use the getContext() API to take a reference to the User's DB we store in the App's context and modify it:

const handler = (request, reply) => {
  // Use the getContext() API to access the App's Context memory:
  const users = request.getContext('users.list');


💻 Live on CodeSandbox:

results matching ""

    No results matching ""