The EJS REST Client is a powerful facility for working with REST APIs. With built-in path prefixing, token management, advanced error handling, convenience methods, and a Promise-based architecture, making API requests has never been easier!
Leveraging the strengths of the EJS HTTP Client 'under-the-hood', it is also possible to dig into the details of requests and responses, whether or not the request was successful.
The api() method is intended for low-level operations, requiring that you encode the arguments yourself and provide any necessary headers.
Always prefer the provided request methods.
Examples
Instantiate RestClient
// Create a RestClient with a base URL and an initial JWT tokenlet rest =newRestClient('/api/v2','Bearer jwt-token-placeholder');
Request Methods
// Make GET requestrest.get('/endpoint');// Make POST requestrest.post('/endpoint');// Make PUT requestrest.put('/endpoint');// Make DELETE requestrest.delete('/endpoint');
Simple Example
// Make a GET request to /users/1rest.get('/users/1').then(response => {let user =response.json();}).catch(error => {console.log(error);});
Exhaustive Example
// Make a GET request to /foo?foo=bar&bar=foorest.get('/foo', { foo:'bar', bar:'foo'}).then(response => {// Successful response (200 <= status < 400)// Check resultif(response.status ===200) {console.log('200 OK! It worked!'); }elseif(response.status ===204) {console.log('204 OK with no body! It worked!'); }elseif(response.status ===304) {console.log('304 Redirected! It worked!'); }// Get response bodylet bodyText =response.text();let bodyObj =response.json();let bodyBuffer =response.arrayBuffer();let bodyBlob =response.blob();// Get the original requestlet originalRequest =response.request;// Check for a header in the responseif(response.headers.has('content-length')) {// Get the value of a header in the responselet contentLength =response.headers.get('content-length'); // case-insensitive header names }}).catch(error => {// Failed response (status >= 400)// Check reason for failureswitch(error.constructor) {// API rejected the request or threw an error (e.g. 500)caseRestClient.Errors.RestError:console.log('Caught RestError: ', error);// Check the reason for rejectionif(error.response.status ===404) {console.log('Page not found!'); }elseif(error.response.status ===500) {console.log('The server threw an error.'); }// Get the body of the responselet bodyText =error.response.text();let bodyObj =error.response.json();let bodyBuffer =error.response.arrayBuffer();let bodyBlob =error.response.blob();break;// HTTP request failed (e.g. could not connect to server, CORS error, etc.)caseRestClient.Errors.NetworkError:console.log('Caught NetworkError: ', error);break; }});
Batching requests
Each of the request methods in RestClient return a Promise object. You can collect these Promise objects into an array, and use the native Promise.all() method to wait for all of them to resolve.
let api =newRestClient('/path/to/api','Bearer my-token');let promises = [];let isLoading =true;// Handle each API response individually...promises.push(this.api.get('/users/1').then(response => {let user =response.json();}));promises.push(this.api.get('/files').then(response => {let files =response.json();}));promises.push(this.api.get('/items').then(response => {let items =response.json();}));// ... and/or handle all API responses at once.Promise.all(promises).then(responses => {// Note: Responses are in the order passed to Promise.all(), // not the order in which they resolve.let user = responses[0].json();let files = responses[1].json();let items = responses[2].json(); isLoading =false;});