Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
bruh Avatar asked Sep 02 '26 12:09

bruh


1 Answers

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.

like image 169
pkawiak Avatar answered Sep 05 '26 01:09

pkawiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!