When attempting to connect to one of our APIs using a Ruby script with a standard library like Net::HTTP, your API key and endpoint might be correct, but the server consistently responds with a 403 Forbidden error.
This issue can be particularly confusing because the exact same API call—with the same endpoint, parameters, and headers—works perfectly when executed from a modern tool like Postman or a cURL command.
The Cause #
The root cause of this error is a protocol mismatch between Ruby’s standard Net::HTTP library and Trestle’s API gateway.
- TrestleIQ API Gateway: Our gateway is a modern service that prefers the HTTP/2 protocol. It enforces a strict set of validation rules for request headers based on this modern standard.
- Ruby Net::HTTP: This standard library is an older client that defaults to the HTTP/1.1 protocol. When it sends a request, its structure can be slightly different from an HTTP/2 request.
The API gateway sees the incoming HTTP/1.1 request from Net::HTTP, flags it as non-compliant with its stricter HTTP/2-based rules, and rejects it with a 403 Forbidden error before the API key is even processed. Modern clients like Postman and cURL work because they can negotiate and use the HTTP/2 protocol, sending a request that the gateway accepts.
The Solution #
The most robust and recommended solution is to use a modern Ruby HTTP library that fully supports the HTTP/2 protocol. This ensures your script can communicate with our gateway in the format it prefers. We recommend using the Faraday gem with the httpx adapter.
Step 1: Update Your Gemfile #
Add faraday and httpx to your project’s Gemfile. The httpx gem is a modern HTTP client that Faraday will use as its “adapter” to handle requests.
gem ‘faraday’
gem ‘httpx’
Step 2: Install the Gems #
Run bundle install from your terminal to install the new gems into your project.
Step 3: Update Your Ruby Script #
Modify your script to use Faraday. The resulting code is cleaner and more reliable. This example shows how to correctly send the API key in the x-api-key header.
require ‘faraday’ require ‘httpx/adapters/faraday’
Faraday.default_adapter = :httpx
response = Faraday.get( ‘https://api.trestleiq.com/3.2/phone?phone=1234567890&phone.country_hint=US‘, nil, { ‘x-api-key’ => ‘YOUR_API_KEY’ } )
puts response.bodyIf you have any additional questions, please reach out to us at support@trestleiq.com.