Creating a REST Endpoint

Using novel new api

You can use the scaffolding CLI to generate a rest endpoint for you. This is the easiest way to create a REST endpoint.

novel new api

Follow the instructions and your new API should be in /app/api.

Manual Creation

1

Create a new directory in `/app/api`

Create a new directory with the kebab-case format that identifies the function of the endpoint uniquely.

A good format is [subject]-[action]

Examples:

  • user-create

  • post-search

2

Create a new index.js or index.ts file inside the directory

Copy the template file below

/app/api/user-create/index.ts
export default function Handler(instance) {
    instance.post('/your/endpoint', handler);

    async function handler(request, reply) {
        // your logic
    }
}
3

Restart Novel

New endpoints are not picked up by the server hot reload. You will need to restart the novel dev server


Enhancements

Routing Options

Using OpenAPI

You can generate OpenAPI schemas based on Fastify's validation and serialization model

/app/api/user-create/schema.json
{
    "body": {
        "type": "object",
        "properties": {
            "id": {
                "type": "string"
            }
        }
    }
}

This is automatically loaded into your route.

Validation

Because of Fastify's validation model, request input is already controlled on a framework level. If you prefer to validate further, you can make use of zod internally like so:

/app/api/user-create/index.ts
import Accounts from 'novel/models/accounts';
import { z } from 'zod';

export default function Handler(instance) {
    instance.post('/your/endpoint', handler);

    async function handler(request, reply) {
        if (Accounts.z.safeParse(request.body)) {
            // your logic
        }
        if (z.safeParse(request.body)) {
            // your logic
        }
    }
}

Route Directives

You can apply authentication, throttling, and other tools via Novel's route directives.

Last updated

Was this helpful?