4

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?
aitchkhan
  • 1,842
  • 1
  • 18
  • 38

3 Answers3

9

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.

The_Switch
  • 193
  • 11
1

In order to create just a RESTful api you can use

npm i -g @adonisjs/cli
# Create a new Adonis app
adonis new project-name --api-only
  • This could do with some further explanation, perhaps you could add some examples of the RESTful functions it creates? – OMGtechy Jan 16 '19 at 17:16
  • It is quite difficult to bring examples, because this command is going to create a scaffolding like the normal cli. However, is not going to add any edge templating for the view (because is RESTful). When you run ``` adonis new project-name --api-only ``` Is going to create a default route with a json response. If you need something more in depth let me know – Jacopo Vendramin Jan 17 '19 at 14:43
0
  1. Yes, You can write rest apis
  2. Can start from by configure database (npm i @adonisjs/lucid) then move to modules (if you are using lucid) and the apis