Last active
December 27, 2019 16:56
-
-
Save swanandp/51d24ca474b10b10c68f2afeb30dc65e to your computer and use it in GitHub Desktop.
Interacting with a RESTful posts service using HTTParty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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