httpmock provides functionality to record both requests to third-party services and their responses.
There are two strategies how you can achieve that: Forwarding and Proxy.
Forwarding Strategy
The forwarding feature is the easier method for intercepting and recording responses from third-party services.
However, it requires you to change the client’s base URL to direct requests to the mock server’s address.
When using the forwarding strategy, your client sends requests to an httpmock mock server.
The mock server forwards requests that match the criteria defined in the
When structure to a predefined target base URL.
Let’s have a look at a basic forwarding example:
You can use the forwarding functionality to record requests sent to the remote service.
Full Example
The following example demonstrates how you can use the forwarding feature to record requests sent to the GitHub API and
the responses it returns.
Proxy Strategy
The proxy feature in httpmock, while functional on its own, is particularly useful for recording
in scenarios where modifying or injecting the base URL used by the client is not possible.
Many SDKs, APIs, and HTTP clients support proxy server configuration. For example,
the reqwest crate allows you to set up a proxy server with the following configuration:
In this example, each request is routed through the proxy server rather than directly to the requested domain host.
The proxy server then tunnels or forwards the request to the target host, which is github.com in this case.
When configured as a proxy, httpmock can intercept, record, and forward both requests and responses.