You wrap a REST API call with auth headers in TypeScript by using the tool() helper from @langchain/core/tools, defining a Zod schema for the tool's input, and implementing the func to make an authenticated fetch request that includes the required Authorization header.
To create a secure, reusable LangChain tool that interacts with a protected REST API, you should use the tool() factory function. This function creates a StructuredTool that accepts a Zod schema for input validation and an asynchronous function containing the fetch logic. The key to authentication is manually adding an Authorization header (or any required custom headers) to the fetch request inside the tool's func. This approach gives you full control over the request, including error handling and response parsing, which is more flexible than trying to configure headers on pre-built request tools .
This method provides complete control over the request, making it robust for production. The API token is securely injected from environment variables at runtime, preventing hardcoding. The tool also includes structured error handling, which is critical for agents to function reliably when external services fail. This pattern is universally applicable, whether you're using a bearer token, API key, or any other authentication scheme. Simply modify the headers object in the fetch call to match your API's requirements.
Context: As an alternative, you could use a pre-built tool like the RequestsGetTool and try to configure its internal request wrapper. However, this approach is generally less flexible and reliable than building a custom tool.
Example: Based on a community discussion, you might attempt to access a tool's internal request wrapper to update its headers . While this can work for simple cases, it is less discoverable and can break if the internal structure of the tool changes in future library versions.
Code Snippet (Less Recommended):
// This is a less robust, exploratory pattern.
import { RequestsGetTool } from "langchain/tools";
const tools = [new RequestsGetTool()];
const requestTool = tools[0];
// Attempt to modify the internal wrapper's headers (structure is not guaranteed).
if (requestTool.requests_wrapper) {
requestTool.requests_wrapper.headers['Authorization'] = `Bearer ${process.env.API_KEY}`;
}
In summary, for wrapping a REST API call with authentication in TypeScript, the custom tool() approach is the most robust, type-safe, and maintainable method. It provides full control over the request and response lifecycle, which is essential for integrating with any protected external service in a LangChain agent.