1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
# Sawyer
To use Sawyer, create a new Agent with a URL endpoint.
```ruby
endpoint = "http://my-api.com"
agent = Sawyer::Agent.new endpoint do |conn|
conn.headers['content-type'] = 'application/vnd.my-api+json'
end
```
From here, we can access the root to get the initial actions.
```ruby
root = agent.start
```
Every request in Sawyer returns a Sawyer::Response. It's very similar
to a raw Faraday::Response, with a few extra methods.
```ruby
# HTTP Headers
root.headers
# HTTP status
root.status
# The JSON Schema
root.schema
# The link relations
root.rels
# The contents (probably empty from the root)
root.data
```
Now, we can access a relation off the root resource.
```ruby
resource = root.data
res = resource.rels[:users].call :query => {:sort => 'login'}
# An array of users
users = res.data
```
This call returns two types of relations: relations on the collection of
users, and relations on each user. You can access the collection
resources from the response.
```ruby
# get the next page of users
res2 = res.rels[:next].call
# page 2 of the users collection
res2.data
```
Each user has it's own relations too:
```ruby
# favorite the previous user
users.each_with_index do |user, index|
res = user.rels[:favorite].call users[index-1]
if !res.success?
puts "#{user.name} could not favorite #{users[index-1].name}"
end
end
```
|