Skip to content

Instantly share code, notes, and snippets.

@swanandp
Created March 29, 2023 15:12
Show Gist options
  • Save swanandp/10272e1eac2930297ce3176c244a8681 to your computer and use it in GitHub Desktop.
Save swanandp/10272e1eac2930297ce3176c244a8681 to your computer and use it in GitHub Desktop.
Ruby Wrapper for Article Service HTTP API
class ArticlesService
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
@auth = {
username: ENV["API_USERNAME"],
password: ENV["API_PASSWORD"],
}
@headers = {
"Content-Type" => "application/json",
}
end
def index
get("articles")
end
def show(article_id)
get("articles/#{article_id}")
end
def create(attributes)
self.class.post(
endpoint("articles"),
default_options.merge(body: attributes.to_json)
)
end
def update(article_id, attributes)
self.class.patch(
endpoint("articles/#{article_id}"),
default_options.merge(body: attributes.to_json)
)
end
def destroy(article_id)
self.class.delete(
endpoint("articles/#{article_id}"),
default_options
)
end
protected
def default_options
{
headers: headers,
basic_auth: auth,
}
end
def endpoint(uri)
"/v1/#{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