Creating a REST Endpoint
Using novel new api
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
2
Create a new index.js or index.ts file inside the directory
Copy the template file below
export default function Handler(instance) {
instance.post('/your/endpoint', handler);
async function handler(request, reply) {
// your logic
}
}
Enhancements
Routing Options
Using OpenAPI
You can generate OpenAPI schemas based on Fastify's validation and serialization model
{
"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:
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?