
Product
Introducing Socket Fix for Safe, Automated Dependency Upgrades
Automatically fix and test dependency updates with socket fixβa new CLI tool that turns CVE alerts into safe, automated upgrades.
fetch-json
Advanced tools
<img src=https://raw.githubusercontent.com/center-key/fetch-json/main/docs/logos.png align=right width=180 alt=logos>
A wrapper around Fetch just for JSON
Why would you fetch anything but json? ;)
fetch-json is a lightweight JavaScript library to reduce the boilerplate code needed to make HTTP calls to JSON endpoints. The minified JS file is under 4 KB.
fetch-json automatically:
Content-Type: application/json
to ensure the correct data type.json()
on the responseJSON.stringify()
params
to the URL of GET
requestscredentials
to 'same-origin'
(support user sessions in frameworks like Grails, Rails, PHP, Django, Flask, etc.)HEAD
request into a simple objectfetch-json is ideal for a JAMstack architecture where "dynamic programming during the request/response cycle is handled by JavaScript, running entirely on the client".
In a web page:
<script src=fetch-json.min.js></script>
or from the jsdelivr.com CDN:
<script src=https://cdn.jsdelivr.net/npm/fetch-json@3.3/dist/fetch-json.min.js></script>
Install package for node:
$ npm install fetch-json
and then import:
import { fetchJson } from 'fetch-json';
Requires minimum node v18.
If you use GitHub Actions, ensure the version of node is set correclty:
- uses: actions/setup-node@v3
with:
node-version: 18
Fetch the NASA Astronomy Picture of the Day:
// NASA APoD
const url = 'https://api.nasa.gov/planetary/apod';
const params = { api_key: 'DEMO_KEY' };
const handleData = (data) =>
console.log('The NASA APoD for today is at:', data.url);
fetchJson.get(url, params).then(handleData);
Example output:
> The NASA APoD for today is at:
> https://apod.nasa.gov/apod/image/2107/LRVBPIX3M82Crop1024.jpg
Create a resource for the planet Jupiter:
// Create Jupiter
const resource = { name: 'Jupiter', position: 5 };
const handleData = (data) =>
console.log('New planet:', data); //http response body as an object literal
fetchJson.post('https://centerkey.com/rest/', resource)
.then(handleData)
.catch(console.error);
For more examples, see the Mocha specification suite:
spec/node.spec.js
(Mocha output for each build under Run npm test
)
To see a website that incorporates fetch-json, check out DataDashboard:
data-dashboard.js.org π
Fetch the NASA Astronomy Picture of the Day:
// NASA APoD
const show = async () => {
const url = 'https://api.nasa.gov/planetary/apod';
const params = { api_key: 'DEMO_KEY' };
const data = await fetchJson.get(url, params);
console.log('The NASA APoD for today is at: ' + data.url);
};
show();
Create a resource for the planet Jupiter:
// Create Jupiter
const create = async (resource) => {
const data = await fetchJson.post('https://centerkey.com/rest/', resource);
console.log('New planet:', data); //http response body as an object literal
};
create({ name: 'Jupiter', position: 5 });
fetch-json calls the native Fetch API.
For comparison, the POST example in section C) Examples to create a planet would be done calling the Fetch API directly with the code:
// Create Jupiter (WITHOUT fetch-json)
const resource = { name: 'Jupiter', position: 5 };
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(resource),
};
const handleData = (data) =>
console.log(data); //http response body as an object literal
fetch('https://centerkey.com/rest/', options)
.then(response => response.json())
.then(handleData)
.catch(console.error);
The example with fetch-json and the example without fetch-json each produce the same output.
The format for using fetch-json is:
fetchJson.get(url, params, options).then(callback);
fetchJson.post(url, resource, options).then(callback);
fetchJson.put(url, resource, options).then(callback);
fetchJson.patch(url, resource, options).then(callback);
fetchJson.delete(url, resource, options).then(callback);
fetchJson.head(url, params, options).then(callback); //headers returned as an object
Notes:
url
parameter is required.Β The other parameters are optional.params
object for fetchJson.get()
is converted into a query string and appended to the url
.resource
object is turned into the body of the HTTP request.options
parameter is passed through to the Fetch API (see the init
documentation on MDN).options
is enhanced with a boolean setting for strictErrors
mode (default false
) that throws an error to .catch()
whenever the HTTP response status is 400 or higher.If you need to programmatically set the method, use the format:
fetchJson.request(method, url, data, options).then(callback);
Where method
is 'GET'
, 'POST'
, 'PUT'
, 'PATCH'
, or 'DELETE'
, and data
represents
either params
or resource
.
Turn on basic logging to the console with:
fetchJson.enableLogger();
To use a custom logger, pass in a function that accepts 9 parameters to log.
To get an array containing the names of the parameters:
fetchJson.getLogHeaders();
// 'Timestamp', 'HTTP', 'Method', 'Domain', 'URL', 'Ok', 'Status', 'Text', 'Type'
The default console output looks like:
2018-09-12T07:20:12.372Z β "request" - "GET" β "api.nasa.gov" β "https://api.nasa.gov/planetary/apod"
2018-09-12T07:20:13.009Z β "response" - "GET" β "api.nasa.gov" β "https://api.nasa.gov/planetary/apod" - true - 200 - "OK" - "application/json"
Turn off logging with:
fetchJson.enableLogger();
The HTTP response body is considered to be JSON if the Content-Type
is "application/json"
or
"text/javascript"
.Β
If the HTTP response body is not JSON, fetch-json passes back
through the promise an object with a bodyText
string field containing response body text.
In addition to the bodyText
field, the object will have the fields: ok
, status
, statusText
,
contentType
, and data
.Β
If an HTML error response is JSON, the data
will contain the parsed JSON.
For example, an HTTP response for an error status of 500 would be converted to an object similar to:
{
ok: false,
status: 500,
statusText: 'INTERNAL SERVER ERROR',
contentType: 'text/html; charset=utf-8',
bodyText: '<!doctype html><html lang=en><body>Server Error</body></html>',
data: null,
}
Every response that is not JSON or is an HTTP error will be consistently formatted like the object above.Β With fetch-json you know the response will always be passed back to you as a consistent, simple object literal.
Use fetchJson.setBaseOptions()
to configure options to be used on future fetchJson requests.
The example below sets the Authorization
HTTP header so it is sent on the subsequent GET and
DELETE requests:
fetchJson.setBaseOptions({ headers: { Authorization: 'Basic WE1MIGlzIGhpZGVvdXM=' } });
fetchJson.get('https://dna-engine.org/api/books/').then(display); //with auth header
fetchJson.delete('https://dna-engine.org/api/books/3/'); //with auth header
To have multiple base options available at the same time, use the FetchJson
class to instantiate
multiple copies of fetchJson
:
import { FetchJson } from 'fetch-json';
const fetchJsonA = new FetchJson({ headers: { From: 'aaa@example.com' } }).fetchJson;
const fetchJsonB = new FetchJson({ headers: { From: 'bbb@example.com' } }).fetchJson;
fetchJsonA.get('https://dna-engine.org/api/books/').then(display); //from aaa@example.com
fetchJsonB.delete('https://dna-engine.org/api/books/3/'); //from bbb@example.com
See the TypeScript declarations at the top of the fetch-json.ts file.
The declarations provide type information about the API. For example, the fetchJson.post()
function returns a Promise for a FetchResponse
:
fetchJson.post(url: string, resource?: RequestData,
options?: FetchOptions): Promise<FetchResponse>
JSDOM does not include fetch
, so you need to add a polyfill.
$ npm install --save-dev whatwg-fetch
See usage of whatwg-fetch
in spec/jsdom.spec.js.
Native support for Fetch API was introduced in node v18 which became the Active LTS version on 2022-10-25.Β If you're using an older version of node, stick with fetch-json v2.7 and in your package.json file declare a dependency on the node-fetch polyfill package.
$ npm install node-fetch
Check out the runScriptsConfig
section in package.json for an
interesting approach to organizing build tasks.
CLI Build Tools for package.json
"Stop trying to make fetch happen without #fetchJson!"
Feel free to submit questions at:
github.com/center-key/fetch-json/issues
FAQs
A wrapper around Fetch just for JSON
The npm package fetch-json receives a total of 658 weekly downloads. As such, fetch-json popularity was classified as not popular.
We found that fetch-json demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Β It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Automatically fix and test dependency updates with socket fixβa new CLI tool that turns CVE alerts into safe, automated upgrades.
Security News
CISA denies CVE funding issues amid backlash over a new CVE foundation formed by board members, raising concerns about transparency and program governance.
Product
Weβre excited to announce a powerful new capability in Socket: historical data and enhanced analytics.