Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AdonisJs be used for REST APIS?

Sorry for a nooby question. I'd ask it anyway! I am playing around with AdonisJs. I understand it is a MVC framework. But I want to write REST APIs using the said framework. I could not find much help on the internet.

I have two questions:

  1. Does the framework support writing REST APIs?
  2. If yes to 1. then what could be the best starting point?
like image 401
aitchkhan Avatar asked Dec 24 '22 19:12

aitchkhan


1 Answers

1. I've created 3 API projects with AdonisJS and think it's ideal for quick setup. It has many functions already included from start, supports database migrations and is pretty well documented in general.

You can create routes easily with JSON responses: http://adonisjs.com/docs/3.2/response

Route.get('/', function * (request, response) {
  const users = yield User.all()
  response.json(users)
})

Or add them to a controller, and even fairly easily add route authentication with token protection (all documented):

Route.post('my_api/v1/authenticate', 'ApiController.authenticate')

Route.group('api', function () {
  Route.get('users', 'ApiController.getUsers')
}).prefix('my_api/v1').middleware('auth:api')

2. Take a look at the official tutorial, you can probably finish it in about half an hour. http://adonisjs.com/docs/3.2/overview#_simplest_example

  • Start with defining some routes and try out echoing simple variables with JSON and just in regular views.
  • Move the test logic to Controllers
  • Read a bit more about the database migrations and add some simple models.
  • Don't forget the Commands and Factory, as you can easily define test data commands there. This will save you a lot of time in the long run.

Just keep in mind that you need to have a server with Node.JS installed to run the system on production (personally I'm keeping it running using a tool like Node Forever JS.

like image 185
The_Switch Avatar answered Dec 28 '22 09:12

The_Switch