A clean API for making JSON requests using the Javascript Fetch API
npm install --save fetch-json
fetch-json
provides functions for each of the HTTP verbs,
and returns promises just like the Fetch API.
All of the examples use this great fake JSON API.
import { getJson } from 'fetch-json';
const apiRoot = 'https://jsonplaceholder.typicode.com';
// As a promise
getJson(apiRoot)
.then(body => {
console.log('success', body);
})
.catch(err => {
console.log('error', err);
});
// Async/Await
async function getFromApi(url) {
try {
const body = await getJson(apiRoot);
console.log('success', body);
} catch(err) {
console.log('error', err);
}
}
getFromApi(apiRoot);
import { postJson } from 'fetch-json';
const apiRoot = 'https://jsonplaceholder.typicode.com';
const requestBody = { foo: 'bar' };
// As a promise
postJson(apiRoot, requestBody)
.then(responseBody => {
console.log('success', responseBody);
})
.catch(err => {
console.log('error', err);
});
// Async/Await
async function postToApi(url, body) {
try {
const responseBody = await postJson(apiRoot, body);
console.log('success', responseBody);
} catch(err) {
console.log('error', err);
}
}
postToApi(apiRoot, requestBody);
import { putJson } from 'fetch-json';
const apiRoot = 'https://jsonplaceholder.typicode.com';
const id = 1001;
const requestBody = { foo: 'baz' };
// As a promise
putJson(`${apiRoot}/${id}`, requestBody)
.then(responseBody => {
console.log('success', responseBody);
})
.catch(err => {
console.log('error', err);
});
// Async/Await
async function putToApi(url, body) {
try {
const responseBody = await putJson(apiRoot, body);
console.log('success', responseBody);
} catch(err) {
console.log('error', err);
}
}
putToApi(`${apiRoot}/${id}`, requestBody);
import { deleteJson } from 'fetch-json';
const apiRoot = 'https://jsonplaceholder.typicode.com';
const id = 1001;
// As a promise
deleteJson(`${apiRoot}/${id}`)
.then(() => {
console.log('success');
})
.catch(err => {
console.log('error', err);
});
// Async/Await
async function deleteFromApi(url) {
try {
await deleteJson(apiRoot);
console.log('success');
} catch(err) {
console.log('error', err);
}
}
deleteFromApi(`${apiRoot}/${id}`);