Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

kitsu

5.2.1 • Public • Published

Kitsu

npm badge npm install badge david badge contributors badge donate badge

travis badge appveyor badge david dev badge cc maintainability badge cc coverage badge

A simple, lightweight & framework agnostic JSON:API client for Kitsu.io and other APIs

Check out the Migration Guide for breaking changes and new features in 5.x

Features

  • JSON-API 1.0 compliant
  • Automatically links relationships to data
  • Works in Node and on the web
  • Uses the Promise API
  • Configurable timeout handling

Node / Browser Support

Package Package
Size*
Node Chrome Firefox Safari Edge IE
kitsu 17.8 kb 6+ 52+ 48+ 10+ 14+
kitsu/legacy 19.9 kb 6+ 4+ 3.5+ 3.2+ 12+ 8+
kitsu/node 14.8 kb 6+

* Including all dependencies, minified & gzipped

Response Comparison

A GET response by a JSON:API server
{
  data: {
    id: '1'
    type: 'articles'
    attributes: {
      title: 'JSON API paints my bikeshed'
    }
    relationships: {
      author: {
        data: {
          id: '42'
          type: 'people'
        }
      }
    }
  }
  included: [
    {
      id: '42'
      type: 'people'
      attributes: {
        name: 'John'
      }
    }
  ]
}
A GET response with kitsu:
{
  data: {
    id: '1'
    type: 'articles'
    title: 'JSON API paints my bikeshed'
    author: {
      id: '42'
      type: 'people'
      name: 'John'
    }
  }
}

Install

Yarn / NPM

yarn add kitsu
npm install kitsu
import Kitsu from 'kitsu'             // ES Modules and Babel
const Kitsu = require('kitsu')        // CommonJS and Browserify
const Kitsu = require('kitsu/legacy') // Legacy IE8+ support
const Kitsu = require('kitsu/node')   // Lighter node-only package

Try it on RunKit

Packd CDN

<script src='https://bundle.run/kitsu@5?name=Kitsu'></script>
<script src='https://bundle.run/kitsu@5/legacy/index.js?name=Kitsu'></script>

Try it on CodePen

Quick Start

// Kitsu.io's API
const api = new Kitsu()
 
// Other JSON:API servers
const api = new Kitsu({
  baseURL: 'https://api.example/2'
})
 
// Using with async/await
const res = await api.get('anime')
 
// Using with Promises
api.get('anime')
  .then(res => { ... })
  .catch(err => { ... })
 
// Fetching resources (get/fetch)
api.fetch('anime')
api.fetch('anime/1')
api.fetch('anime/1/episodes')
 
// Creating resources (post/create)
api.create('post', {
  content: 'some content'
})
 
// Updating resources (patch/update)
api.update('post', {
  id: '1',
  content: 'new content'
})
 
// Deleting resources
api.remove('post', 1)

More Examples

If you're working with Kitsu.io's API, their API docs lists all available resources with their attributes and relationships

API

Table of Contents

Kitsu

Creates a new kitsu instance

Parameters

  • options Object Options (optional, default {})
    • options.baseURL string Set the API endpoint (default https://kitsu.io/api/edge)
    • options.headers Object Additional headers to send with requests
    • options.camelCaseTypes boolean If true, the type value will be camelCased, e.g library-entries and library_entries become libraryEntries (default true)
    • options.resourceCase string kebab, snake or none. If kebab, /libraryEntries will become /library-entries. If snake, /libraryEntries will become /library_entries, If none, /libraryEntries will be unchanged (default kebab)
    • options.pluralize boolean If true, /user will become /users in the URL request and type will be pluralized in post, patch and delete requests - user -> users (default true)
    • options.timeout number Set the request timeout in milliseconds (default 30000)

Examples

Using with Kitsu.io's API

const api = new Kitsu()

Using another API server

const api = new Kitsu({
  baseURL: 'https://api.example.org/2'
})

Setting headers

const api = new Kitsu({
  headers: {
    'User-Agent': 'MyApp/1.0.0 (github.com/username/repo)',
    Authorization: 'Bearer 1234567890'
  }
})

delete

Remove a resource (alias remove)

Parameters
  • model string Model to remove data from
  • id (string | number) Resource ID to remove
  • headers Object Additional headers to send with request (optional, default {})
Examples

Remove a user's post

api.delete('posts', 123)

Returns Object JSON-parsed response

get

Fetch resources (alias fetch)

Parameters
  • model string Model to fetch data from
  • params Object JSON-API request queries (optional, default {})
  • headers Object Additional headers to send with request (optional, default {})
Examples

Getting a resource with JSON:API parameters

api.get('users', {
  fields: {
    users: 'name,birthday'
  },
  filter: {
    name: 'wopian'
  }
})

Getting a collection of resources with their relationships

api.get('anime', {
  include: 'categories'
})

Getting a single resource by ID (method one)

api.get('anime/2', {
  include: 'categories'
})

Getting a single resource by ID (method two)

api.get('anime', {
  include: 'categories',
  filter: { id: '2' }
})

Getting a resource's relationship data only

api.get('anime/2/categories')

Handling errors (async/await)

try {
  const { data } = await api.get('anime')
} catch (err) {
  // Array of JSON:API errors: http://jsonapi.org/format/#error-objects
  if (err.errors) err.errors.forEach(error => { ... })
  // Error type (Error, TypeError etc.)
  err.name
  // Error message
  err.message
  // Axios request parameters
  err.config
  // Axios response parameters
  err.response
}

Handling errors (Promises)

api.get('anime')
  .then(({ data }) => { ... })
  .catch(err => {
    // Array of JSON:API errors: http://jsonapi.org/format/#error-objects
    if (err.errors) err.errors.forEach(error => { ... })
    // Error type (Error, TypeError etc.)
    err.name
    // Error message
    err.message
    // Axios request parameters
    err.config
    // Axios response parameters
    err.response
  })

Returns Object JSON-parsed response

headers

Get the current headers or add additional headers

Examples

Get all headers

api.headers

Get a single header's value

api.headers['User-Agent']

Add or update a header's value

api.headers['Authorization'] = 'Bearer 1234567890'

Returns Object All the current headers

patch

Update a resource (alias update)

Parameters
  • model string Model to update data in
  • body Object Data to send in the request
  • headers Object Additional headers to send with request (optional, default {})
Examples

Update a post

api.update('posts', {
  id: '12345678',
  content: 'Goodbye World'
})

Returns Object JSON-parsed response

plural

If pluralization is enabled (default, see Kitsu constructor docs) then pluralization rules can be added

Examples

Adding an uncountable pluralization rule

api.plural.plural('paper') //=> 'papers'
api.plural.addUncountableRule('paper')
api.plural.plural('paper') //=> 'paper'

post

Create a new resource (alias create)

Parameters
  • model string Model to create a resource under
  • body Object Data to send in the request
  • headers Object Additional headers to send with request (optional, default {})
Examples

Create a post on a user's profile feed

api.create('posts', {
  content: 'Hello World',
  targetUser: {
    id: '42603',
    type: 'users'
  },
  user: {
    id: '42603',
    type: 'users'
  }
})

Returns Object JSON-parsed response

self

Get the authenticated user's data

Note Requires the JSON:API server to support filter[self]=true

Parameters
  • params Object JSON-API request queries (optional, default {})
  • headers Object Additional headers to send with request (optional, default {})
Examples

Get the authenticated user's resource

api.self()

Using JSON:API parameters

api.self({
  fields: {
    users: 'name,birthday'
  }
})

Returns Object JSON-parsed response

Contributing

See CONTRIBUTING

Releases

See CHANGELOG

License

All code released under MIT

install

npm i kitsu

Downloadsweekly downloads

543

version

5.2.1

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar