Instantly share code, notes, and snippets.

Embed
What would you like to do?
Interacting with a RESTful posts service using HTTParty
class PostsService
include HTTParty
base_uri "https://api.example.com"
read_timeout 5 # always have timeouts!
# debug_output $stdout # for quick access during debugging
attr_reader :auth, :headers
def initialize(user)
@auth = {
username: ENV["API_USERNAME"],
password: ENV["API_PASSWORD"],
}
@headers = {
"Content-Type" => "application/json",
"X-User-ID" => user.tracking_id,
"X-Tags" => "Name:#{user.full_name}",
"Authorisation" => "Bearer:#{user.oauth_token}",
}
end
def index
get("posts")
end
def show(post_id)
get("posts/#{post_id}")
end
def create(attributes)
self.class.post(
endpoint("posts"),
default_options.merge(body: attributes.to_json)
)
end
def update(post_id, attributes)
self.class.patch(
endpoint("posts/#{post_id}"),
default_options.merge(body: attributes.to_json)
)
end
def destroy(post_id)
self.class.delete(
endpoint("posts/#{post_id}"),
default_options
)
end
protected
def default_options
{
headers: headers,
digest_auth: auth,
}
end
def endpoint(uri)
"/v2/#{uri}"
end
def get(uri)
self.class.get(
endpoint(uri),
default_options
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment