For handling API calls I have a small snippet I'm copying from project to project. I decided to clean it up, make more generic and share it. It is intended to be a starting point, so you might want to customize it to your custom needs.
What it does?
It is a simple wrapper around native fetch
. (If you need a polyfill isomorphic-fetch is a great one.)
- For successful requests it will parse the response and return it.
- When HTTP error occurs (It detects errors based on request's HTTP status.) it will throw a custom error with status code, error message and response (parsed if it is a JSON).
- If request never gets resolved, same custom error will be thrown but response will be set to
null
and status code toREQUEST_FAILED
.
Please note that function will return a Promise so you need to handle how it resolves.
Code
It is written as a native ES2015 module, which means you may need to transpile it depending on your browser support policy.
// ------------------------------------------------------ //
// Simple JavaScript API wrapper
// https://muffinman.io/simple-javascript-api-wrapper
// ------------------------------------------------------ //
// For demo purposes I'm using this awesome Star Wars API
;
// Custom API error to throw
// API wrapper function
;
;
Usage
fetchResource
accepts two arguments, mandatory URL and optional options to be passed to the fetch
request. If you wrap each API request in a function with it's specific options it will be easier to maintain.
Few examples:
// Simple get request
// Post request with payload
// Put request, with file data and custom headers
Then you call newly created API functions, they will return a Promise, so you need to define then
(and catch
for errors).
Demo
I've cooked a small demo to show it in practice, in which I used free Star Wars API.
Feel free to play with it on CodePen.
Comments (4)