How to use HTTP GET APIS?

Asked

Viewed 94 times

0

I have an API that performs object manipulation through a link, the parameters are passed on that link. I would like to know how I can use it or create a javascript method to run this link.

1 answer

2

Voce must use Xmlhttprequest (ajax), or fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) and pass the url that returns the json in the request.

However, the correct way to pass parameters through GET is through the URI, called 'Query Strings''

example of a class in js:

class HttpRequest {

    static get (url, params = {}) {
        return HttpRequest.request("GET", url, params);
    }

    static delete (url, params = {}) {
        return HttpRequest.request("DELETE", url, params);
    }

    static post (url, params = {}) {
        return HttpRequest.request("POST", url, params);
    }

    static put (url, params = {}) {
        return HttpRequest.request("PUT", url, params);
    }

    static request(method, url, params={}){
        return new Promise((resolve, reject)=>{
            let ajax = new XMLHttpRequest();

            ajax.open(method.toUpperCase(), url);

            ajax.onerror = event =>{
                reject(event);
            }

            ajax.onload = () => {
                let obj = {};
                try {
                    obj = JSON.parse(ajax.responseText);
                } catch(e) {
                    reject(e);
                }
                resolve(obj);
            };

            ajax.setRequestHeader("Content-Type","application/json");
            ajax.send(JSON.stringify(params));

        });
    }
}

I hope I helped! Hug!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.