Devour JSON-API Client

3.2.0 · active · verified Tue Apr 21

Devour Client is a lightweight, framework-agnostic JavaScript client for consuming JSON:API compliant APIs. It simplifies the often painful process of manually serializing and deserializing JSON:API resources, providing clear conventions for pagination, filtering, sparse fields, and relationships. Currently stable at version 3.2.0, it focuses on offering a simple yet comprehensive feature set that differentiates it from other JavaScript JSON:API client implementations by abstracting away the complexities of the specification. While a specific release cadence isn't defined, the project sees regular maintenance and dependency updates. It provides a flexible middleware stack and configurable options for common API patterns like pluralization, trailing slashes, and authentication.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes Devour Client, defines two JSON:API models ('post' and 'comment'), and demonstrates common CRUD operations (findAll, find, create, update, destroy) and arbitrary requests against a hypothetical API endpoint.

import JsonApi from 'devour-client'

// Bootstrap the client with your API endpoint
const jsonApi = new JsonApi({apiUrl:'http://your-api-here.com'})

// Define a model schema matching your JSON:API resources
jsonApi.define('post', {
  title: '',
  content: '',
  tags: [],
  comments: {
    jsonApi: 'hasMany',
    type: 'comments'
  }
})

jsonApi.define('comment', {
  comment: '',
  post: {
    jsonApi: 'belongsTo',
    type: 'posts'
  }
})

async function runExample() {
  try {
    // Fetch all posts with pagination
    const postsPage2 = await jsonApi.findAll('post', {page: {number: 2}});
    console.log('Posts on page 2:', postsPage2.data.map(p => p.title));

    // Fetch a single post by ID
    const post = await jsonApi.find('post', '5');
    console.log('Post 5:', post.data.title);

    // Create a new post
    const newPost = await jsonApi.create('post', {
      title: 'Hello from Devour!',
      content: 'This is some content for a new post.',
      tags: ['devour', 'jsonapi']
    });
    console.log('Created post:', newPost.data.title);

    // Update an existing post
    const updatedPost = await jsonApi.update('post', {
      id: newPost.data.id,
      title: 'Updated title',
      content: 'New content for the updated post',
      tags: ['devour', 'update']
    });
    console.log('Updated post:', updatedPost.data.title);

    // Delete a post
    await jsonApi.destroy('post', updatedPost.data.id);
    console.log('Deleted post:', updatedPost.data.id);

    // Make an arbitrary request
    const customRequest = await jsonApi.request('http://your-api-here.com/some-custom-endpoint', 'GET', { queryParam: 'value' });
    console.log('Custom request result:', customRequest);

  } catch (error) {
    console.error('API Error:', error.errors || error.message);
  }
}

runExample();

view raw JSON →