Skip to content

Instantly share code, notes, and snippets.

@Mozart2234
Created September 21, 2023 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mozart2234/1892c233560fd24176ba058d5c84854d to your computer and use it in GitHub Desktop.
Save Mozart2234/1892c233560fd24176ba058d5c84854d to your computer and use it in GitHub Desktop.
Easy Broker requests
require 'json'
require 'net/http'
class ApiClient
class ApiError < StandardError; end
def initialize(base_url, authorization_token = nil)
@base_url = base_url
@authorization_token = authorization_token
end
def get(endpoint)
uri = URI.join(@base_url, endpoint)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
request["accept"] = 'application/json'
request['X-Authorization'] = @authorization_token if @authorization_token
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise ApiError, "Failed to fetch data from the API"
end
JSON.parse(response.body)
end
end
require 'rspec'
require 'webmock/rspec'
require_relative '../lib/api_client'
RSpec.describe ApiClient do
let(:api_url) { 'https://api.todo.com' }
let(:authorization_token) { 'your_authorization_token' }
let(:client) { ApiClient.new(api_url, authorization_token) }
before do
WebMock.disable_net_connect!
end
after do
WebMock.allow_net_connect!
end
describe '#get' do
it 'fetches data from the API' do
expected_response = { 'userId' => 1, 'id' => 1, 'title' => 'Test Task', 'completed' => false }
# Stub the API request and define the response
stub_request(:get, "#{api_url}/todo").with(
headers: {
'accept' => 'application/json',
'X-Authorization'=>'your_authorization_token'
}).
to_return(status: 200, body: expected_response.to_json, headers: {})
data = client.get('/todo')
expect(data).to eq(expected_response)
end
it 'raises an error for non-existent endpoints' do
# Stub the API request to return a 404 error
stub_request(:get, "#{api_url}/nonexistent").with(
headers: {
'accept' => 'application/json',
'X-Authorization' => authorization_token
}
).to_return(status: 404)
expect { client.get('/nonexistent') }.to raise_error(ApiClient::ApiError, /Failed to fetch data from the API/)
end
end
end
# Gemfile
source 'https://rubygems.org'
gem 'rspec'
gem 'webmock'
require_relative "./api_client"
# Example usage:
API_URL = "https://api.stagingeb.com"
AUTHORIZATION_TOKEN = ENV["AUTH_TOKEN"]
client = ApiClient.new(API_URL, AUTHORIZATION_TOKEN)
begin
data = client.get("/v1/properties?page=1&limit=20")
puts "Data from the API:"
puts JSON.pretty_generate(data)
titles = data["content"].map { |property| property["title"] }
puts "Titles: #{titles}"
rescue StandardError => e
puts "Error: #{e.message}"
end
require 'rspec'
require_relative '../lib/api_client'
RSpec.describe 'API Usage' do
let(:api_url) { 'https://api.stagingeb.com' }
let(:authorization_token) { 'l7u502p8v46ba3ppgvj5y2aad50lb9' }
before do
WebMock.disable_net_connect!
end
after do
WebMock.allow_net_connect!
end
it 'successfully fetches and processes data from the API' do
# Stub the API request for the specific endpoint you intend to use
stub_request(:get, "#{api_url}/v1/properties?page=1&limit=20").with(
headers: { 'accept' => 'application/json', 'X-Authorization' => authorization_token }
).to_return(
status: 200,
body: { 'content' => [{ 'title' => 'Property 1' }, { 'title' => 'Property 2' }] }.to_json,
headers: { 'Content-Type' => 'application/json' }
)
# Your usage code goes here
client = ApiClient.new(api_url, authorization_token)
data = client.get('/v1/properties?page=1&limit=20')
expect(data['content'].count).to eq(2)
expect(data['content'][0]['title']).to eq('Property 1')
expect(data['content'][1]['title']).to eq('Property 2')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment