fetch-json (2024)

fetch-json (1)

A wrapper around Fetch just for JSON

fetch-json (2)fetch-json (3)fetch-json (4)

Why would you fetch anything but json? ;)

A) Make REST Easy

fetch-json is a lightweight JavaScript library to reduce the boilerplate code needed to makeHTTP calls to JSON endpoints.The minified JS file is under 4 KB.

fetch-json automatically:

  1. Adds the HTTP header Content-Type: application/json to ensure the correct data type
  2. Runs .json() on the response
  3. Serializes the body payload with JSON.stringify()
  4. Appends params to the URL of GET requests
  5. Sets credentials to 'same-origin' (support user sessions in frameworks like Grails, Rails, PHP, Django, Flask, etc.)
  6. Converts the HTTP text response to JSON if it's not already JSON (convenient for handling HTTP errors)
  7. Maps HTTP response headers from a HEAD request into a simple object

fetch-json is ideal for a JAMstack architecture where "dynamicprogramming during the request/response cycle is handled by JavaScript, running entirely on theclient".

B) Setup

1. Web browser

In a web page:

<script src=fetch-json.min.js></script>

or from the jsdelivr.com CDN:

<script src=https://cdn.jsdelivr.net/npm/[email protected]/dist/fetch-json.min.js></script>

2. Node.js server

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

C) Examples

1. HTTP GET

Fetch the NASA Astronomy Picture of the Day:

// NASA APoDconst 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

2. HTTP POST

Create a resource for the planet Jupiter:

// Create Jupiterconst resource = { name: 'Jupiter', position: 5 };const handleData = (data) => console.log('New planet:', data); //http response body as an object literalfetchJson.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 📊

D) Examples Using async/await

1. HTTP GET

Fetch the NASA Astronomy Picture of the Day:

// NASA APoDconst 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();

2. HTTP POST

Create a resource for the planet Jupiter:

// Create Jupiterconst 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 });

E) Leverages Fetch API

fetch-json calls the nativeFetch API.

For comparison, the POST example in section C) Examples to create a planet would bedone calling the Fetch APIdirectly 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 literalfetch('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 sameoutput.

F) API

1. API — HTTP Request

The format for using fetch-json is:

GET

fetchJson.get(url, params, options).then(callback);

POST

fetchJson.post(url, resource, options).then(callback);

PUT

fetchJson.put(url, resource, options).then(callback);

PATCH

fetchJson.patch(url, resource, options).then(callback);

DELETE

fetchJson.delete(url, resource, options).then(callback);

HEAD (HTTP response headers)

fetchJson.head(url, params, options).then(callback); //headers returned as an object

Notes:

  1. Only the url parameter is required. The other parameters are optional.
  2. The params object for fetchJson.get() is converted into a query string and appended to the url.
  3. The resource object is turned into the body of the HTTP request.
  4. The options parameter is passed through to the Fetch API (see the init documentation on MDN).
  5. 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.

Dynamic HTTP method

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 representseither params or resource.

2. API — logging

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();

G) Response Text and Errors Converted to JSON

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 backthrough 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 objectsimilar 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.

H) Base Options

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 andDELETE requests:

fetchJson.setBaseOptions({ headers: { Authorization: 'Basic WE1MIGlzIGhpZGVvdXM=' } });fetchJson.get('https://dna-engine.org/api/books/').then(display); //with auth headerfetchJson.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 instantiatemultiple copies of fetchJson:

import { FetchJson } from 'fetch-json';const fetchJsonA = new FetchJson({ headers: { From: '[email protected]' } }).fetchJson;const fetchJsonB = new FetchJson({ headers: { From: '[email protected]' } }).fetchJson;fetchJsonA.get('https://dna-engine.org/api/books/').then(display); //from [email protected]fetchJsonB.delete('https://dna-engine.org/api/books/3/'); //from [email protected]

I) TypeScript Declarations

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>

J) Fetch polyfills

1. Add Fetch to JSDOM

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.

2. Legacy Node.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

K) Build Environment

Check out the runScriptsConfig section in package.json for aninteresting approach to organizing build tasks.

CLI Build Tools for package.json

  • 🎋 add-dist-header: Prepend a one-line banner comment (with license notice) to distribution files
  • 📄 copy-file-util: Copy or rename a file with optional package version number
  • 📂 copy-folder-util: Recursively copy files from one folder to another folder
  • 🪺 recursive-exec: Run a command on each file in a folder and its subfolders
  • 🔍 replacer-util: Find and replace strings or template outputs in text files
  • 🔢 rev-web-assets: Revision web asset filenames with cache busting content hash fingerprints
  • 🚆 run-scripts-util: Organize npm package.json scripts into groups of easy to manage commands
  • 🚦 w3c-html-validator: Check the markup validity of HTML files using the W3C validator

"Stop trying to make fetch happen without #fetchJson!"

Feel free to submit questions at:
github.com/center-key/fetch-json/issues

MIT License

fetch-json (2024)
Top Articles
What is a Zombie Second Mortgage?
postalidph.com
How To Start a Consignment Shop in 12 Steps (2024) - Shopify
Jail Inquiry | Polk County Sheriff's Office
Mchoul Funeral Home Of Fishkill Inc. Services
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Alpha Kenny Buddy - Songs, Events and Music Stats | Viberate.com
His Lost Lycan Luna Chapter 5
Culver's Flavor Of The Day Monroe
Craigslist Dog Kennels For Sale
Best Restaurants Ventnor
Springfield Mo Craiglist
Non Sequitur
Letter F Logos - 178+ Best Letter F Logo Ideas. Free Letter F Logo Maker. | 99designs
Patrick Bateman Notebook
Carolina Aguilar Facebook
Happy Life 365, Kelly Weekers | 9789021569444 | Boeken | bol
Craigslist Org Appleton Wi
Employee Health Upmc
Shadbase Get Out Of Jail
Southland Goldendoodles
Asteroid City Showtimes Near Violet Crown Charlottesville
Jesus Revolution Showtimes Near Regal Stonecrest
Hdmovie2 Sbs
4Oxfun
Villano Antillano Desnuda
Danielle Moodie-Mills Net Worth
Keshi with Mac Ayres and Starfall (Rescheduled from 11/1/2024) (POSTPONED) Tickets Thu, Nov 1, 2029 8:00 pm at Pechanga Arena - San Diego in San Diego, CA
WPoS's Content - Page 34
Funky Town Gore Cartel Video
Rugged Gentleman Barber Shop Martinsburg Wv
FREE Houses! All You Have to Do Is Move Them. - CIRCA Old Houses
Fox And Friends Mega Morning Deals July 2022
Gideon Nicole Riddley Read Online Free
Appleton Post Crescent Today's Obituaries
Polk County Released Inmates
Jasgotgass2
Author's Purpose And Viewpoint In The Dark Game Part 3
Atom Tickets – Buy Movie Tickets, Invite Friends, Skip Lines
Bunkr Public Albums
SF bay area cars & trucks "chevrolet 50" - craigslist
Kutty Movie Net
R: Getting Help with R
Arcanis Secret Santa
Dancing Bear - House Party! ID ? Brunette in hardcore action
The Quiet Girl Showtimes Near Landmark Plaza Frontenac
Theater X Orange Heights Florida
Rubmaps H
M Life Insider
Bumgarner Funeral Home Troy Nc Obituaries
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5409

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.