ApiStruct consists of two main interfaces: ApiStruct::Client and ApiStruct::Entity. The ApiStruct::Client class is aimed at using the same interface for describing requests to different APIs. The ApiStruct::Entity enables you to use ApiStruct clients in ORM-like style.
Add this line to your application's Gemfile:
gem'api_struct'And then execute:
$ bundle
Or install it yourself as:
$ gem install api_struct
Initialize APIs routes:
ApiStruct::Settings.configuredo |config|
config.endpoints={first_api: {root: 'http://localhost:3000/api/v1',headers: {'content-type': 'application/json','Authorization': 'Bearer TOKEN'}},second_api: {root: 'http://localhost:3001/api/v1',params: {token: 'Default token'}}}endEndpoint wrapper
classPostsClient < ApiStruct::Clientfirst_api:postsdefshow(id)get(id)enddefindexgetenddefuser_posts(user_id,post_id=nil)get(post_id,prefix: [:users,user_id])# alias:# get(post_id, prefix: '/users/:id', id: user_id)enddefcustom_path(user_id)get(path: 'users_posts/:user_id',user_id: user_id)endendUsage:
PostsClient.new.get(1)# -> /posts/1Returns Resultmonad
# => Success({:id=>1, :title=>"Post"})Other methods from sample:
post_client=PostsClient.newpost_client.index# -> /postspost_client.user_posts(1)# -> /users/1/postspost_client.user_posts(1,2)# -> /users/1/posts/2post_client.custom_path(1)# -> /users_posts/1/Response serializer
classUser < ApiStruct::Entityclient_serviceUsersClientclient_serviceAuthorsClient,prefix: true,only: :index# alias:# client_service AuthorsClient, prefix: :prefix, except: :indexattr_entity:name,:idendclassUsersClient < ApiStruct::Clientfirst_api:usersdefshow(id)get(id)endendclassAuthorsClient < ApiStruct::Clientfirst_api:authorsdefindexgetendendUsage:
user=User.show(1)# => {"id"=>1, "name"=>"John"}Call methods from prefixed clients:
users=User.authors_client_index# or# users = User.prefix_indexResponse serializers with related entities:
classNetwork < ApiStruct::Entityclient_serviceNetworkClientattr_entity:name,:idattr_entity:state, &:to_symhas_entity:super_admin,as: UserendclassNetworkClient < ApiStruct::Clientfirst_api:networksdefshow(id)get(id)endendUsage:
network=Network.show(1)# => {"id"=>1, "name"=>"Main network", "state"=>"active", "super_admin"=>{"id"=>1, "name"=>"John"}}network.state# => :activeclassAuthdefself.call# Get a token..endendclassAuthHeaderValuedefself.call{"Authorization": "Bearer #{Auth.call}"}endendclassPostClient < ApiStruct::Clientfirst_api:postsdefupdate(id,post_data)put(id,json: post_data,headers: AuthHeaderValue.call)endendBug reports and pull requests are welcome on GitHub at https://github.com/rubygarage/api_struct.
The gem is available as open source under the terms of the MIT License.
RubyGarage is a leading software development and consulting company in Eastern Europe. Our main expertise includes Ruby and Ruby on Rails, but we successfully employ other technologies to deliver the best results to our clients. Check out our portfolio for even more exciting works!
