百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
J

json_api_client

> 开发工具
开源

构建符合 jsonapi.org 定义的规范的客户端库

363 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

构建符合 jsonapi.org 定义的规范的客户端库

JsonApiClient

This gem is meant to help you build an API client for interacting with REST APIs as laid out by http://jsonapi.org. It attempts to give you a query building framework that is easy to understand (it is similar to ActiveRecord scopes).

Note: master is currently tracking the 1.0.0 specification. If you're looking for the older code, see 0.x branch

Usage

You will want to create your own resource classes that inherit from JsonApiClient::Resource similar to how you would create an ActiveRecord class. You may also want to create your own abstract base class to share common behavior. Additionally, you will probably want to namespace your models. Namespacing your model will not affect the url routing to that resource.

ruby
module MyApi
  # this is an "abstract" base class that
  class Base  true
u.save

u.new_record?
# => false

u = MyApi::Person.find(1).first
u.update_attributes(
  a: "b",
  c: "d"
)

u.persisted?
# => true

u.destroy

u.destroyed?
# => true
u.persisted?
# => false

u = MyApi::Person.create(
  a: "b",
  c: "d"
)

All class level finders/creators should return a JsonApiClient::ResultSet which behaves like an Array and contains extra data about the api response.

Handling Validation Errors

See specification

Out of the box, json_api_client handles server side validation only.

…

For now we are assuming that error sources are all parameters.

If you want to add client side validation, I suggest creating a form model class that uses ActiveModel's validations.

Meta information

See specification

If the response has a top level meta data section, we can access it via the meta accessor on ResultSet.

ruby
# Example response:
{
  "meta": {
    "copyright": "Copyright 2015 Example Corp.",
    "authors": [
      "Yehuda Katz",
      "Steve Klabnik",
      "Dan Gebhardt"
    ]
  },
  "data": {
    // ...
  }
}
articles = Articles.all

articles.meta.copyright
# => "Copyright 2015 Example Corp."

articles.meta.authors
# => ["Yehuda Katz", "Steve Klabnik", "Dan Gebhardt"]

Top-level Links

See specification

If the resource returns top level links, we can access them via the links accessor on ResultSet.

ruby
articles = Articles.find(1)
articles.links.related

Nested Resources

You can force nested resource paths for your models by using a belongs_to association.

Note: Using belongs_to is only necessary for setting a nested path unless you provide shallow_path: true option.

ruby
module MyApi
  class Account  raises ArgumentError

# makes request to /users/2/accounts/1
MyApi::Account.where(user_id: 2).find(1)
# => returns ResultSet

# makes request to /customers/1
MyApi::Customer.find(1)
# => returns ResultSet

# makes request to /users/2/customers/1
MyApi::Customer.where(user_id: 2).find(1)
# => returns ResultSet

you can also override param name for belongs_to association

ruby
module MyApi
  class Account  returns ResultSet

Custom Methods

You can create custom methods on both collections (class method) and members (instance methods).

ruby
module MyApi
  class User  

user = MyApi::User.find(1)
# makes PUT request to /users/1/verify?foo=bar
user.verify(foo: 'bar')

Fetching Includes

See specification

If the response returns a compound document, then we should be able to get the related resources.

…

Sparse Fieldsets

See specification

…

Sorting

See specification

ruby
# makes request to /people?sort=age
youngest = Person.order(:age).all

# also makes request to /people?sort=age
youngest = Person.order(age: :asc).all

# makes request to /people?sort=-age
oldest = Person.order(age: :desc).all

Paginating

See specification

Requesting

ruby
# makes request to /articles?page=2&per_page=30
articles = Article.page(2).per(30).to_a

# also makes request to /articles?page=2&per_page=30
articles = Article.paginate(page: 2, per_page: 30).to_a

# keep in mind that page number can be nil - in that case default number will be applied
# also makes request to /articles?page=1&per_page=30
articles = Article.paginate(page: nil, per_page: 30).to_a

Note: The mapping of pagination parameters is done by the query_builder which is customizable.

Browsing

If the response contains additional pagination links, you can also get at those:

ruby
articles = Article.paginate(page: 2, per_page: 30).to_a
articles.pages.next
articles.pages.last

Library compatibility

A JsonApiClient::ResultSet object should be paginatable with both kaminari and will_paginate.

Filtering

See specifiation

ruby
# makes request to /people?filter[name]=Jeff
Person.where(name: 'Jeff').all

Schema

You can define schema within your client model. You can define basic types and set default values if you wish. If you declare a basic type, we will try to cast any input to be that type.

The added benefit of declaring your schema is that you can access fields before data is set (otherwise, you'll get a NoMethodError).

Note: This is completely optional. This will set default values and handle typecasting.

Example

ruby
class User  nil

u.is_admin
# => false

u.points_accrued
# => 0

# casting
u.average_points_per_day = "0.3"
u.average_points_per_day
# => 0.3

Types

The basic types that we allow are:

  • :int or :integer
  • :float
  • :string
  • :time - *Note: Include the time zone in the string if it's different than local time.
  • :boolean - Note: we will cast the string version of "true" and "false" to their respective values

Also, we consider nil to be an acceptable value and will not cast the value.

Note : Do not map the primary key as int.

Customizing

Paths

You can customize this path by changing your resource's table_name:

…

ruby class Resource < JsonApiClient::Resource self.raise_on_blank_find_param = true end


## Contributing

Contributions are welcome! Please fork this repo and send a pull request. Your pull request should have:

* a description about what's broken or what the desired functionality is
* a test illustrating the bug or new feature
* the code to fix the bug

Ideally, the PR has 2 commits - the first showing the failed test and the second with the fix - although this is not
required. The commits will be squashed into master once accepted.

### Set up development locally

- With a decent ruby version:
  ```shell
  bundle install
  appraisal install
  • Run all tests for that ruby version:

    bash
    appraisal rake
  • For more info on appraisal:

    bash
    appraisal help

Changelog

See changelog

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyjson-apijsonapiclientruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类开发工具
定价开源

> 相关工具

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具