Skip to content

Instantly share code, notes, and snippets.

@droduit
Last active November 12, 2019 15:30
Show Gist options
  • Save droduit/db4a583d4ae6cf3ef2e998aa28a4cfad to your computer and use it in GitHub Desktop.
Save droduit/db4a583d4ae6cf3ef2e998aa28a4cfad to your computer and use it in GitHub Desktop.
Simple way to send HTTP requests to an API in JavaScript.
/*
=========================================================
Here is how to use the code
========================================================= */
const jsonApi = api("https://jsonplaceholder.typicode.com/");
// GET, request to "https://jsonplaceholder.typicode.com/todos/1"
jsonApi.get('todos/1', json => console.log(json));
// POST, request to "https://jsonplaceholder.typicode.com/posts"
jsonApi.post('posts', {userId: 1, title: "post title", body: "post content"}, response => console.log(response), error => console.log(error));
// The same can be done with put, patch and delete
jsonApi.put('posts/1', bodyRequest, [successCallback], [errorCallback]);
jsonApi.patch('posts/1', bodyRequest, [successCallback], [errorCallback]);
jsonApi.delete('posts/1', [successCallback], [errorCallback]);
// =========================================================
/*
Below you find 3 versions of the same code, just fetching the data using 3 different ways:
1. Async - Await
2. Promises
3. JQuery
*/
// Async-await version
const api = (baseUrl) => {
'use strict';
const request = (endpoint, method, body, callbackSuccess, callbackError) => {
const fetchOptions = {
method: method,
body : body == null ? null : JSON.stringify(body),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}
const invokeFunctionIfDefined = (func, param) => {
if (func != null && func instanceof Function) {
func(param);
}
}
try {
var response = await fetch(baseUrl+endpoint, fetchOptions);
if (response.ok) {
try {
var json = await response.json();
invokeFunctionIfDefined(callbackSuccess, json);
return json;
} catch (error) {
invokeFunctionIfDefined(callbackSuccess, await response.text());
}
}
} catch (error) {
invokeFunctionIfDefined(callbackError, error);
}
};
return {
get : (endpoint, callbackSuccess, callbackError = null) =>
request(endpoint, "GET", null, callbackSuccess, callbackError),
post : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "POST", body, callbackSuccess, callbackError),
put : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "PUT", body, callbackSuccess, callbackError),
patch : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "PATCH", body, callbackSuccess, callbackError),
delete: (endpoint, callbackSuccess = null, callbackError = null) =>
request(endpoint, "DELETE", null, callbackSuccess, callbackError)
}
};
// Promise version
const api = (baseUrl) => {
'use strict';
const request = (endpoint, method, body, callbackSuccess, callbackError) => {
const fetchOptions = {
method: method,
body : body == null ? null : JSON.stringify(body),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}
const invokeFunctionIfDefined = (func, param) => {
if (func != null && func instanceof Function) {
func(param);
}
}
return fetch(baseUrl+endpoint, fetchOptions)
.then(response => response.ok ? response.text() : Promise.reject({err: response.status}) )
.then(text => {
try {
return JSON.parse(text);
} catch (error) {
invokeFunctionIfDefined(callbackSuccess, text);
}
})
.then(json => {
invokeFunctionIfDefined(callbackSuccess, json);
})
.catch(error => {
invokeFunctionIfDefined(callbackError, error);
});
};
return {
get : (endpoint, callbackSuccess, callbackError = null) =>
request(endpoint, "GET", null, callbackSuccess, callbackError),
post : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "POST", body, callbackSuccess, callbackError),
put : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "PUT", body, callbackSuccess, callbackError),
patch : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "PATCH", body, callbackSuccess, callbackError),
delete: (endpoint, callbackSuccess = null, callbackError = null) =>
request(endpoint, "DELETE", null, callbackSuccess, callbackError)
}
};
// jQuery version
const api = (baseUrl) => {
'use strict';
const request = (endpoint, method, body, callbackSuccess, callbackError) => {
const invokeFunctionIfDefined = (func, param) => {
if (func != null && func instanceof Function) {
func(param);
}
}
var request = $.ajax({
url: baseUrl+endpoint,
method: method,
data: body == null ? null : JSON.stringify(body),
processData: false,
contentType: 'application/json'
});
request.done(text => {
if (callbackSuccess == null || !(callbackSuccess instanceof Function)) {
return;
}
try {
callbackSuccess(JSON.parse(text));
} catch (error) {
callbackSuccess(text);
}
});
request.fail( (jqXHR, textStatus) => {
if (callbackError != null && callbackError instanceof Function) {
callbackError(error);
}
});
};
return {
get : (endpoint, callbackSuccess, callbackError = null) =>
request(endpoint, "GET", null, callbackSuccess, callbackError),
post : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "POST", body, callbackSuccess, callbackError),
put : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "PUT", body, callbackSuccess, callbackError),
patch : (endpoint, body, callbackSuccess = null, callbackError = null) =>
request(endpoint, "PATCH", body, callbackSuccess, callbackError),
delete: (endpoint, callbackSuccess = null, callbackError = null) =>
request(endpoint, "DELETE", null, callbackSuccess, callbackError)
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment