2 apps - frontend and backend api


#1

Hi,
I am building a backend api in Adonis and a frontend app in Adonis. What is the best way to connect to the api in the frontend app?
Do I create controllers > models that call the api? ie. Models that don’t connect to a database.
Do I use axios?
Any help is really appreciated. I’m totally new to Adonis…


#2

Personally I think that your question is too broad to be answered here

I suggest that you should see the tutorial Build a Twitter Clone With Adonis and Vue by @ammezie

What You’ll Learn:

  • How to use AdonisJs
  • Building an API with Adonis
  • Building a frontend with Vue
  • Consume an API with Vue

What You’ll Build:

  • An AdonisJs API
  • A Vue frontend

Hope this helps


#3

@yosvelquintero Thanks for the reply, perhaps I was unclear in my question.
I am after any examples of best practice when using a third-party api as the ‘model’ within an Adonis app.
The tutorial you listed is great (finished it a couple of days ago) however it uses Vue as the frontend (spa) and I’d rather use Adonis.


#4

Adonis isn’t really a “frontend” framework, but I think I understand what you’re asking.

You mentioned axios, so I’ll assume you’re familiar with it. Simply require it in your controller or set it up globally.

From there, make sure that your controller method has async in front of it, and then you can set the response of your external API call to a variable and use it later. Like this:

async myFunc ({ view }) {
const myData = await axios({
method: 'get',
url: 'path-to-api',
headers: {
'AUTH-HEADERS': 'your-auth-headers'
}
})

view.render('myView', {
myData: myData
})

Then you can access the myData variable inside your myView.edge file using the double curly braces. Like so {{ myData }}. Don’t forget to access the API’s data structures appropriately, since myData is only the response from your API call. You’ll need to add myData.data at the very least.

Hope this helps!


#5

Thanks Tim!

Exactly what I was after with my less than optimal post :slight_smile:


#6

Figured. I had spent half the evening trying to figure out how to do it myself. Glad it was helpful :slight_smile: