Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

kitsu

Package Overview
Dependencies
Maintainers
1
Versions
172
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

kitsu

Simple & lightweight JSON-API client for Kitsu and other compliant APIs

  • 5.0.0-beta.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4.3K
decreased by-12.24%
Maintainers
1
Weekly downloads
 
Created
Source

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 4.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

Install

yarn add kitsu
npm install kitsu

Node / Browser Support

PackagePackage
Size
NodeChromeFirefoxSafariEdgeIE
Default17.9 kb6+49+57+10.1+15+
Legacy19.9 kb6+4+3+3.1+12+8+
Node14.5 kb6+

Response Comparison

A GET response by a JSON:API server returns:

{
  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 request with kitsu returns:

{
  data: {
    id: '1'
    type: 'articles'
    title: 'JSON API paints my bikeshed'
    author: {
      id: '42'
      type: 'people'
      name: 'John'
    }
  }
}

Quick Start

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

const api = new Kitsu()                   // For kitsu.io developers

const api = new Kitsu({                   // For other JSON:API servers
  baseURL: 'https://api.example/2'        // e.g https://api.example/2
})

const { data } = await api.get('anime')   // Using with async/await

api.get('anime')                          // Using with Promises
  .then(({ data }) => { ... })
  .catch(err => throw err)

// Fetching resources with get() or fetch()
api.get('anime', { params }, { headers }) // Collection of resources
api.get('anime/1')                        // Single resource
api.get('anime/1/episodes')               // Single resource's relationship

// Creating resources with post() or create()
api.create('post', {
  content: 'some content'
})

// Updating resources with patch() or 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

Parameters

  • options Object Options
    • 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

// If using Kitsu.io's API
const api = new Kitsu()
// If using another API server
const api = new Kitsu({
  baseURL: 'https://api.example.org/2'
})
// Set a `user-agent` and an `authorization` token
const api = new Kitsu({
  headers: {
    'User-Agent': 'MyApp/1.0.0 (github.com/username/repo)',
    Authorization: 'Bearer 1234567890'
  }
})
get

Fetch resources Aliases: 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

// Get a specific user's name & birthday
api.get('users', {
  fields: {
    users: 'name,birthday'
  },
  filter: {
    name: 'wopian'
  }
})
// Get a collection of anime resources and their categories
api.get('anime', {
  include: 'categories'
})
// Get a single resource and its relationships by ID (method one)
api.get('anime', {
  include: 'categories',
  filter: { id: '2' }
})
// Get a single resource and its relationships by ID (method two)
api.get('anime/2', {
  include: 'categories'
})
// Get a resource's relationship data only
api.get('anime/2/categories')
// Handling errors (async/await)
// http://jsonapi.org/format/#error-objects
try {
  const { data } = api.get('anime')
} catch (err) {
  if (err.errors) err.errors.forEach(error => {
      console.log(error) // Prints JSON:API error object
  })
}
// Handling errors (Promise)
// http://jsonapi.org/format/#error-objects
api.get('anime')
  .then(res => res.data)
  .catch(err => {
    if (err.errors) err.errors.forEach(error => {
      console.log(error) // Prints JSON:API error object
    })
  })

Returns Object JSON-parsed response

headers

Get the current headers or add additional headers

Examples

// Receive all the headers
api.headers
// Receive a specific header
api.headers['User-Agent']
// Add or update a header
api.headers['Authorization'] = 'Bearer 1234567890'

Returns Object All the current headers

isAuth

Check if the client is authenticated (oAuth2/Authorization header)

Examples

if (api.isAuth) console.log('Authenticated')
else console.log('Not authenticated')

Returns boolean

patch

Update a resource Aliases: 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 user's post (Note: For Kitsu.io, posts cannot be edited 30 minutes after creation)
api.update('posts', {
  id: '12345678',
  content: 'Goodbye World'
})

Returns Object JSON-parsed response

post

Create a new resource Aliases: 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

// Post to a user's own profile
api.create('posts', {
  content: 'Hello World',
  targetUser: {
    id: '42603',
    type: 'users'
  },
  user: {
    id: '42603',
    type: 'users'
  }
})

Returns Object JSON-parsed response

remove

Remove a resource

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

// Delete a user's post
api.remove('posts', 123)

Returns Object JSON-parsed response

self

Get the authenticated user's data Note: Requires the JSON:API server to support filter[self]=true

Parameters

Examples

// Receive all attributes
api.self()
// Receive a sparse fieldset
api.self({
  fields: 'name,birthday'
})

Returns Object JSON-parsed response

Contributing

See CONTRIBUTING

Releases

See CHANGELOG

License

All code released under MIT

Keywords

FAQs

Package last updated on 24 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc