bruh bruh - 2 months ago 15
reST (reStructuredText) Question

Simulating an API call with Javascript

I want to simulate an API calls. I am writing an application in VueJS, and I'm currently retrieving my data from a hardcoded JSON file I created.

For example, from my

App.vue
:

<template>
<p>{{ teams.yankees.city }}</p> // Will output "New York"
</template>

<script>
import teams from './teams.json'

export default {
data() {
return { teams }
}
}
</script>


From my
teams.json
file:

{
"yankees": [
{ "city": "New York", "established": 1901, "worldSeries": 27 }
]
...
}


I can as of now successfully retrieve my data from my local JSON file - but how can I instead retrieve data using "function stubs", in a way that will allow me to swap in real restful API calls in the future?

Is there a barebones resource somewhere, that shows how to set up a mock rest service that calls my local JSON file?

Answer

For using json files as your mock data, you don't need anything but a simple http server. Put teams.json file somewhere in your project directory and serve it using http server of your choice, for example this simple, zero-configuration command-line http server.

Then access your mocked data using Vue resource plugin:

{
  this.$http.get('http://localhost:8080/teams.json').then((response) => {
    // success callback
  }, (response) => {
    // error callback
  });
}

I guess you don't want to hardcode urls in your service calls. What I like to do is to have a mapping file where I define resource names and map them to concrete paths:

{
  teams: 'http://localhost:8080/teams.json'
}

This way I can switch between different resource locations without changing my business code.

If you need something more sophisticated you can either build it yourself or check out existing services, for example mockable.io or apiary.io.