
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Add this line to your application's Gemfile:
gem 'network-client'
And then execute:
$ bundle
Or install the gem directly:
$ gem install network-client
Given this client set up:
require "network-client"
client = Network::Client.new(endpoint: 'https://jsonplaceholder.typicode.com')
We can perform the following requests:
client.get '/todos/10'
#=> #<struct Network::Client::Response code=200, body={"userId"=>1, "id"=>10, "title"=>"illo est ...", "completed"=>true}>
client.post '/todos', params: { title: 'foo bar', completed: 'false', userId: 1 }.to_json
#=> #<struct Network::Client::Response code=201, body={"title"=>"foo bar", "completed"=>false, "userId"=>1, "id"=>201}>
client.patch '/todos/10', params: { title: 'new title' }.to_json
#=> #<struct Network::Client::Response code=200, body={"userId"=>1, "id"=>10, "title"=>"new title", "completed"=>true}>
client.put '/todos/43', params: { completed: false }.to_json
#=> #<struct Network::Client::Response code=200, body={"completed"=>false, "id"=>43}>
client.delete '/todos/25'
#=> #<struct Network::Client::Response code=200, body={}>
As appears in previous examples, the returned value of each successful request is a Response
struct.
It holds the response's HTTP code and body parsed as JSON.
response = client.get '/posts/30'
response.code #=> 200
response.body #=> { "userId"=>3, "id"=>30, "title"=>"a quo magni similique perferendis", "body"=>"alias dolor cumque ..." }
Since this is mainly JSON web client, Accept
and Content-Type
headers are set to json by default.
You can override them and set extra headers during initialization by providing headers:
argument:
headers = { 'X-SPECIAL-KEY' => '123456' }
client = Network::Client.new(endpoint: 'https://api.example.com', headers: headers)
Or on request basis with the headers:
argument too:
client.get 'posts/', headers: { 'X-SPECIAL-KEY' => '123456' }
# using `username` and `password` named parameters when initialized:
client = Network::Client.new(endpoint: 'https://api.example.com',
username: 'ABC',
password: '999')
client.username #=> "ABC"
client.password #=> "999"
# or via `#set_basic_auth`:
client.set_basic_auth('John Doe', '112233')
client.username #=> "John Doe"
client.password #=> "112233"
client.set_bearer_auth(token: 'e08f7739c3abb78c')
client.bearer_token
#=> "e08f7739c3abb78c"
client.set_token_auth(header_value: 'Token token=sec_key_aZcNRzoCMpmdMEP4OEeDUQ==')
client.auth_token_header
#=> "Token token=sec_key_aZcNRzoCMpmdMEP4OEeDUQ=="
You can set the user agent header during initialization:
client = Network::Client.new(endpoint: 'https://maps.googleapis.com', user_agent: 'App Service')
client.user_agent #=> "App Service"
Or later on via #set_user_agent
method:
client.set_user_agent('Gateway Server')
client.user_agent #=> "Gateway Server"
The default user agent is Network Client
.
Set the tries:
named argument to define the number of tries when request fails with one of the retryable errors.
client = Network::Client.new(endpoint: 'https://api.foursquare.com', tries: 3)
client.tries #=> 3
The default #tries
is 2.
To retrieve or extend the list of triable errors through #errors_to_recover
:
client.errors_to_recover
#=> [Net::HTTPTooManyRequests, Net::HTTPServerError, Net::ProtocolError, Net::HTTPBadResponse,Net::ReadTimeout, Net::OpenTimeout, Errno::ECONNREFUSED, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError, SocketError]
client.errors_to_recover << Net::HTTPRequestTimeOut
#=> [Net::HTTPTooManyRequests, Net::HTTPServerError, Net::ProtocolError, Net::HTTPBadResponse,Net::ReadTimeout, Net::OpenTimeout, Errno::ECONNREFUSED, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError, SocketError, Net::HTTPRequestTimeOut]
The list of errors_to_propagate
takes precedence over errors_to_recover
, and they are not retried.
You can retrieve them for rescue in your application layer, and extend them too.
client.errors_to_propagate
#=> [Net::HTTPRequestURITooLong, Net::HTTPMethodNotAllowed]
client.errors_to_propagate << Net::HTTPNotAcceptable
#=> [Net::HTTPRequestURITooLong, Net::HTTPMethodNotAllowed, Net::HTTPNotAcceptable]
Be careful not to add ancestor error class (higher in the inheritance chain) as it will prevent any of it's descendant classes from getting retried. Unless this is an intended behavior, of course.
When Rails
is in scope, it's logger will be used by default.
If not, then it defaults to a fallback logger that writes to STDOUT
.
Additionally, you can override with your custom logger by supplying block to #set_logger
like so:
client = Network::Client.new(endpoint: 'https://api.foursquare.com')
client.set_logger { Logger.new(STDERR) }
client.logger
#=> #<Logger:0x007fb3cd136d38 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x007fb3cd136d10 @datetime_format=nil>, @formatter=nil, @logdev=#<Logger::LogDevice:0x007fb3cd136c98 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<IO:<STDERR>>, @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x007fb3cd136c70>>>
For more details, please refer to the API documentation.
Bug reports and pull requests are very much appreciated at Github.
MIT.
FAQs
Unknown package
We found that network-client demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.