In this tutorial, we are using Adonis 4.0 to build a RESTful application. Adonis is an open source Node.js web framework with primary focus on simplicity and ease of use. It was inspired by Laravel and borrows a lot of features from the PHP framework. The framework comes with features such as Job queues, an authentication system, integration with email systems, data validation, and supports Lucid ORM. The framework is created and maintained by Aman Virk

Requirements

The following tools are used in this article:
Adonis 4.0
Git
MySQL
Postman
Node (A basic knowledge of Node and ES6/7)

You can go ahead and install Node, Git, and Postman. We will walk through installing Adnois and MySQL in the tutorial.

What are RESTful APIs?

A REST (REpresentational State Transfer) web service is one way of providing communication between applications and services on the Internet. An API (Application Programming Interface) is a set of protocols or tools used in building an application. RESTful APIs allows system to communicate via HTTP using HTTP verbs like GET, POST, PUT and DELETE. GET is used to retrieve resources, POST is used to store new resources, PUT is used to update an existing resources and DELETE is delete an existing resource. For this article, our resources will be Books.

Let’s create a new application. Open your terminal or command prompt and type the following command:

    # if you don't have Adonis CLI installed on your machine. 
    $ npm i -g @adonisjs/cli

    # Create a new Adonis app
    $ adonis new adonisjs-restful-api --api-only

Make sure you have Git installed for the adonis command to work

After that is done, navigate into application’s directory and start your server to test if all is working:

    $ cd adonisjs-restful-api

    $ adonis serve --dev

Open Postman and make a request to http://127.0.0.1:3333. You should see this sample JSON.

Migrations and Models

Before we start with the migrations, make sure you have your database set-up for this application and add the credentials to the .env file in the project’s root directory.

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=adonis-restful
    DB_USERNAME=root
    DB_PASSWORD=adonis

Let’s get started with the our first migration and model – Book. A book should have a Title, an ISBN, an Author, a Publisher and a Creation Date. We will be using the Adonis CLI to create the files and put them in the appropriate folder. To create the Book model, we can run:

    adonis make:model Book --migration

The --``migration “ argument tells adonis CLI to create a migration file along with the model file.

Go to the database/migrations directory and modify the migration file as follow:

    // <timestamp>_book_schema.js

    'use strict'

    const Schema = use('Schema')

    class BookSchema extends Schema {
      up () {
        this.create('books', (table) => {
          table.increments()
          table.string('title').nullable()
          table.string('isbn').nullable()
          table.string('publisher_name').nullable()
          table.string('author_name').nullable()
          table.timestamps()
        })
      }

      down () {
        this.drop('books')
      }
    }

    module.exports = BookSchema

up() runs when we migrate while down() runs when we rollback.

Before you migrate the table, let’s install the MySql module:

    $ npm install --save mysql

Now, we can go ahead and migrate:

    $ adonis migration:run

Next, go to the model file called Book.js in app/Models and add references to the table and primary key:

    'use strict'

    const Model = use('Model')

    class Book extends Model {
      static get table () {
        return 'books'
      }

      static get primaryKey () {
        return 'id'
      }
    }

    module.exports = Book

Routes and controllers

Let’s work on the endpoints of our application: create, fetch the list, fetch a single resource, update and delete. In our start/routes.js file, we will just do this:

    'use strict'

    const Route = use('Route')
    const Book = use('App/Models/Book')

    Route.group(() => {
      Route.post('books', async ({ request, response }) => {
        const bookInfo = request.only(['title', 'isbn', 'publisher_name', 'author_name'])

        const book = new Book()
        book.title = bookInfo.title
        book.isbn = bookInfo.isbn
        book.publisher_name = bookInfo.publisher_name
        book.author_name = bookInfo.author_name

        await book.save()

        return response.status(201).json(book)
      })

      Route.get('books', async ({ response }) => {
        let books = await Book.all()

        return response.json(books)
      })

      Route.get('books/:id', async ({ params, response }) => {
        const book = await Book.find(params.id)

        return response.json(book)
      })

      Route.put('books/:id', async ({ params, request, response }) => {
        const bookInfo = request.only(['title', 'isbn', 'publisher_name', 'author_name'])

        const book = await Book.find(params.id)
        book.title = bookInfo.title
        book.isbn = bookInfo.isbn
        book.publisher_name = bookInfo.publisher_name
        book.author_name = bookInfo.author_name

        await book.save()

        return response.status(200).json(book)
      })

      Route.delete('books/:id', async ({ params, response }) => {
        const book = await Book.find(params.id)
        if (!book) {
          return response.status(404).json(null)
        }
        await book.delete()

        return response.status(204).json(null)
      })
    }).prefix('api/v1')

The routes created in the start/routes.js will be prefixed with api/v1. If you noticed from the code, we grouped all our routes because they share the prefix api/v1.

When your application grows pretty large, you might want to move this entire logic to a different controller class. You can use the CLI tools to make controllers:

    adonis make:controller BookController

The CLI tool will ask you what the controller is for. Select Http Request

Check your app/Controllers/Http``/ directory and directory where you will discover a controller called BookController``.js has been created.

Replace BookController.js with the logic originally in your route file:

    'use strict'

    const Book = use('App/Models/Book')
    class BookController {
      async index ({response}) {
        let books = await Book.all()

        return response.json(books)
      }

      async show ({params, response}) {
        const book = await Book.find(params.id)

        return response.json(book)
      }

      async store ({request, response}) {
        const bookInfo = request.only(['title', 'isbn', 'publisher_name', 'author_name'])

        const book = new Book()
        book.title = bookInfo.title
        book.isbn = bookInfo.isbn
        book.publisher_name = bookInfo.publisher_name
        book.author_name = bookInfo.author_name

        await book.save()

        return response.status(201).json(book)
      }

      async update ({params, request, response}) {
        const bookInfo = request.only(['title', 'isbn', 'publisher_name', 'author_name'])

        const book = await Book.find(params.id)
        if (!book) {
          return response.status(404).json({data: 'Resource not found'})
        }
        book.title = bookInfo.title
        book.isbn = bookInfo.isbn
        book.publisher_name = bookInfo.publisher_name
        book.author_name = bookInfo.author_name

        await book.save()

        return response.status(200).json(book)
      }

      async delete ({params, response}) {
        const book = await Book.find(params.id)
        if (!book) {
          return response.status(404).json({data: 'Resource not found'})
        }
        await book.delete()

        return response.status(204).json(null)
      }
    }

    module.exports = BookController

Then you can leave your route as thin as possible:

    const Route = use('Route')

    Route.group(() => {
      Route.post('books', 'BookController.store')
      Route.get('books', 'BookController.index')
      Route.get('books/:id', 'BookController.show')
      Route.put('books/:id', 'BookController.update')
      Route.delete('books/:id', 'BookController.delete')
    }).prefix('api/v1')

Let’s head back to Postman again and start testing out these new routes and the controller functionalities:

  • The store method in BookController is responsible for handling HTTP POST requests to api/v1/books, and handles creation.

  • The index method in BookController is responsible for handling HTTP GET requests to api/v1/books, and handles retrieving all the book resources available.

  • The show method in BookController is responsible for handling HTTP GET requests to api/v1/books, and handles retrieving of a particular book resource.

  • The update method in BookController is responsible for handling HTTP PUT requests to api/v1/books, and handles updating of a particular book resource. It will only update it if the resource is available, otherwise it will return an HTTP 404 Not Found error.

  • Lastly, the delete method in BookController is responsible for handling HTTP DELETE requests to api/v1/books, and handles deleting of a particular book resource. If the resource is available it will delete it and return an HTTP 204 No Content, otherwise it will return an HTTP 404 Not Found.

Please find the Github repository here.

Conclusion

Adonis is an awesome Node.js framework that brings joy and stability over anything else. I hope building this RESTful API opens your eyes to Adonis.

If you have any questions or observations, feel free to drop them in the comments section below. I would be happy to respond to you.

About Chris Nwamba

Chris is a JavaScript preacher. He also strives to make something out of other languages. Tech Writer. Dev Evangelist. Speaker.