0

I'm starting a new project that consists of backend (REST Framework - Django) and frontend (Vue app).

First I'm trying to figure out the "best" way to handle API requests. For example - not to have to remember the urls and to keep the DRY principle. I decided to create an API wrapper inside src/api/api.js that looks like this:

import urljoin from 'url-join'
import axios from 'axios'

axios.defaults.headers.common = {'Authorization': `Token 6b84bc681af39c7d92eab0aa78da2195e497a425`}

const API_URL = 'http://127.0.0.1:8000/api'

class Api {
  getProducts(params) {
    return axios.get(urljoin(API_URL, 'product'), { params: params })
  }
}

export default Api

And I plan to use this Api class anywhere in my project this way:

<script>

import Api from '../../api/api'

const api = new Api()

export default {
  mounted() {
    api.getProducts().then((resp) => {
      console.log(resp)
    })
  }
}
</script>

Is there some pattern or common way to handle such API? What would you do differently?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.