Building an API with AdonisJS V5

Create a REST API with AdonisJS V5, Lucid models and validation.

When you need a backend for a front end app you might reach for Express and start wiring together a router, an ORM and a validation library yourself. AdonisJS gives you all of that out of the box. Version 5 is a full rewrite in TypeScript and it makes building a REST API really simple.

Let's build out a small posts API with AdonisJS V5, Lucid (the Adonis ORM) and SQLite.

Step 1: Create the project

Create a new app with the Adonis TypeScript starter:

npm init adonis-ts-app@latest my-api

It will ask you a few questions:

  • Select the project structure: choose api. This skips views, sessions and static files that you won't need for an API.
  • Enter the project name: press enter to use my-api.
  • Setup eslint and prettier: your call.

Then start the dev server:

cd my-api
node ace serve --watch

Ace is the Adonis command line tool. The --watch flag restarts the server when files change. Visiting http://localhost:3333 will show { "hello": "world" }, which comes from start/routes.ts.

Step 2: Set up Lucid and the database

Lucid is installed as its own package and then configured with Ace:

npm i @adonisjs/lucid
node ace configure @adonisjs/lucid

Pick SQLite when it asks for a database driver (PostgreSQL or MySQL work the same way). This creates config/database.ts and adds DB_CONNECTION=sqlite to your .env file. SQLite also needs its driver package:

npm i sqlite3

The configure step will also tell you to validate the new environment variable. Add it to env.ts:

// env.ts
import Env from "@ioc:Adonis/Core/Env"
export default Env.rules({
...
DB_CONNECTION: Env.schema.string(),
})

Note: SQLite stores the database at tmp/db.sqlite3, so make sure the tmp folder exists in your project.

Step 3: Create the Post model and migration

The -m flag creates a migration along with the model:

node ace make:model Post -m

This gives us app/Models/Post.ts and a new file in database/migrations. First add the columns to the migration:

// database/migrations/1618234567890_posts.ts
import BaseSchema from "@ioc:Adonis/Lucid/Schema"
export default class Posts extends BaseSchema {
protected tableName = "posts"
public async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments("id")
table.string("title").notNullable()
table.text("body").notNullable()
table.timestamps(true)
})
}
public async down() {
this.schema.dropTable(this.tableName)
}
}

Then add the same columns to the model. Each @column decorator maps a class property to a column in the table:

// app/Models/Post.ts
import { DateTime } from "luxon"
import { BaseModel, column } from "@ioc:Adonis/Lucid/Orm"
export default class Post extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public title: string
@column()
public body: string
@column.dateTime({ autoCreate: true })
public createdAt: DateTime
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime
}

Now run the migration to create the table:

node ace migration:run

Step 4: Add the routes

Resourceful routes register all of the CRUD routes for a resource in one line. Calling apiOnly() removes the create and edit routes, which only exist to render HTML forms.

// start/routes.ts
import Route from "@ioc:Adonis/Core/Route"
Route.resource("posts", "PostsController").apiOnly()

Run node ace list:routes to see what was registered:

GET /posts PostsController.index
POST /posts PostsController.store
GET /posts/:id PostsController.show
PUT /posts/:id PostsController.update
DELETE /posts/:id PostsController.destroy

Step 5: Create the controller

node ace make:controller Post

Adonis pluralizes the name for you, so this creates app/Controllers/Http/PostsController.ts. Each method receives the HTTP context, which we destructure to get the request, response and route params:

// app/Controllers/Http/PostsController.ts
import { HttpContextContract } from "@ioc:Adonis/Core/HttpContext"
import { schema, rules } from "@ioc:Adonis/Core/Validator"
import Post from "App/Models/Post"
const postSchema = schema.create({
title: schema.string({ trim: true }, [rules.maxLength(255)]),
body: schema.string(),
})
export default class PostsController {
public async index() {
return Post.all()
}
public async store({ request, response }: HttpContextContract) {
const data = await request.validate({ schema: postSchema })
const post = await Post.create(data)
return response.created(post)
}
public async show({ params }: HttpContextContract) {
return Post.findOrFail(params.id)
}
public async update({ params, request }: HttpContextContract) {
const post = await Post.findOrFail(params.id)
const data = await request.validate({ schema: postSchema })
post.merge(data)
await post.save()
return post
}
public async destroy({ params, response }: HttpContextContract) {
const post = await Post.findOrFail(params.id)
await post.delete()
return response.noContent()
}
}

Whatever a controller method returns is sent back as JSON. findOrFail throws when no row matches, which Adonis turns into a 404 response for us.

The postSchema describes what a valid request body looks like. request.validate checks the body against it and returns the validated data, or throws and responds with a 422 and a list of errors. Because it only returns the fields in the schema, nobody can sneak extra columns like id into Post.create.

Step 6: Test it with curl

Create a post:

curl -X POST http://localhost:3333/posts \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"title": "Hello Adonis", "body": "My first post"}'
# {"title":"Hello Adonis","body":"My first post","created_at":"...","updated_at":"...","id":1}

Then list all posts or grab one by id:

curl http://localhost:3333/posts
curl http://localhost:3333/posts/1

Sending a body without a title shows the validation errors:

curl -X POST http://localhost:3333/posts \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"body": "No title"}'
# {"errors":[{"rule":"required","field":"title","message":"required validation failed"}]}

Note: The Accept: application/json header tells Adonis to send validation errors back as JSON.

That's a full CRUD API with validation in only a few files. Next you can hook up a front end to it, add authentication with @adonisjs/auth, or deploy it to any host that runs Node.

Have some feedback on this post? .