API with Javascript

3

I would like to know how do I make an API in the javascript language to return data like JSON. I need it so I want to make a mobile application.

    
asked by anonymous 30.07.2015 / 00:38

1 answer

2

One way to make an API is to create a separate JavaScript file containing one or more objects declaring the functions you need in your API.

For example, below is a dummy API representing a simple calculator:

// calculadora. js
var calculadora = {
    somar: function (a, b) {
        return a + b;
    },

    multiplicar: function (a, b) {
        return a * b;
    }
};

To use your API you first need to import the API's JavaScript file into the page through a script tag:

<script type="text/javascript" src="pasta_da_api/calculadora.js" />

Once you've done this, you can now call the declared methods in your API like this:

var soma = calculadora.somar(a, b);

var produto = calculadora.multiplicar(a, b);
    
30.07.2015 / 01:03