Skip to content
We use cookies to improve the site and measure traffic. See our Cookie Policy. You can accept or reject non-essential cookies.
July 10, 2026
5 min read
Article

Integrate ToolYour API in Node.js

Author

Abdul Wahab Raza

Founder, ToolYour

Integrate ToolYour API in Node.js

Node.js backend developers often need to integrate robust external utilities into their products. The ToolYour API provides a comprehensive catalog of tools, from file converters to SEO analyzers, accessible via a straightforward RESTful interface. This guide details a minimal Node.js integration pattern for the ToolYour REST API, focusing on how to set up your environment, make API calls, handle responses, and manage your quota effectively. By following these steps, you can quickly bring the power of the ToolYour API Node.js integration into your applications.

Prerequisites

To begin integrating the ToolYour API into your Node.js application, ensure you have the following in place:

  • Node.js Environment: You need an active Node.js installation (LTS version recommended) and a package manager like npm or yarn configured on your development machine.
  • ToolYour Account: A free ToolYour account is required to generate an API key. If you don't have one, you can sign up at https://www.toolyour.com/signup.
  • ToolYour API Key: After creating an account, generate an API key from your dashboard. Navigate to https://www.toolyour.com/dashboard/api-keys to create and manage your keys. All API keys for a single account share the same monthly quota.

The free plan includes 500 successful requests per month, shared across both the REST API and the Model Context Protocol (MCP). It also enforces a throughput limit of 5 successful requests per minute. Your quota resets on the 1st of each calendar month. For a deeper dive into authentication methods beyond simple API key usage, refer to the ToolYour REST API Authentication Guide.

Environment variables for API keys

Protecting your API keys is a critical security practice. Instead of hardcoding keys directly into your application, use environment variables. This prevents sensitive credentials from being exposed in your codebase and makes it easier to manage keys across different deployment environments.

To set your ToolYour API key as an environment variable, name it TOOLYOUR_API_KEY. The API key will start with the prefix ty_.

For local development, you can set this in your shell before running your Node.js application:

export TOOLYOUR_API_KEY="ty_YOUR_ACTUAL_API_KEY_HERE"
node your-application.js

In a production environment, your hosting provider or container orchestration system will have specific methods for managing environment variables.

Within your Node.js application, you can access this key using process.env:

const TOOLYOUR_API_KEY = process.env.TOOLYOUR_API_KEY;

if (!TOOLYOUR_API_KEY) {
    console.error('Error: TOOLYOUR_API_KEY environment variable is not set.');
    process.exit(1);
}

The ToolYour API expects the API key to be sent in the X-Api-Key HTTP header for all authenticated requests.

Example fetch call structure

The ToolYour API exposes over 200 tools, ranging from AI utilities like summarizers to file converters and SEO tools, all accessible via a consistent RESTful interface. To interact with these tools, you'll make HTTP POST requests to specific tool endpoints. The core of your Node.js integration will involve using a standard HTTP client, such as Node.js's built-in fetch API (available in Node.js v18+).

Here's a generic example of how to structure a fetch call to a ToolYour API endpoint. This example assumes you want to invoke a tool that takes a JSON payload as input.

const TOOLYOUR_API_KEY = process.env.TOOLYOUR_API_KEY;

if (!TOOLYOUR_API_KEY) {
    console.error('Error: TOOLYOUR_API_KEY environment variable is not set.');
    process.exit(1);
}

async function invokeTool(toolId, inputData) {
    const apiUrl = `https://api.toolyour.com/v1/tools/${toolId}`;

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Api-Key': TOOLYOUR_API_KEY, // Your API key goes here
            },
            body: JSON.stringify(inputData),
        });

        // Handle response (covered in the next section)
        if (!response.ok) {
            const errorBody = await response.json();
            console.error(`API Error (${response.status}):`, errorBody);
            throw new Error(`ToolYour API request failed with status ${response.status}`);
        }

        const data = await response.json();
        return data;

    } catch (error) {
        console.error('Error invoking ToolYour tool:', error);
        throw error;
    }
}

// Example usage:
// Replace 'some-tool-id' with an actual tool ID from the ToolYour catalog,
// e.g., 'image-to-jpg-converter' or 'text-stats-analyzer'.
// Consult the official documentation at https://www.toolyour.com/developers/docs/calling-tools
// to find specific tool IDs and their required input schemas.
const myToolId = 'example-tool-id'; // Placeholder: e.g., 'text-stats'
const myInputData = {
    // This structure varies by tool.
    // For 'text-stats', it might be:
    // text: 'This is some sample text for analysis.'
    // For 'docx-to-pdf-converter', it might be:
    // file_url: 'https://example.com/document.docx'
    // Refer to tool schemas in the documentation.
    param1: 'value1',
    param2: 'value2',
};

// Uncomment to run the example
/*
invokeTool(myToolId, myInputData)
    .then(result => {
        console.log('Tool invocation successful:', result);
    })
    .catch(error => {
        console.error('Failed to invoke tool:', error);
    });
*/

To find specific tool IDs and understand their required input schemas, always refer to the official ToolYour developers documentation at https://www.toolyour.com/developers/docs/calling-tools. This resource provides detailed information for each tool, including its unique identifier, expected input parameters, and output structure.

It's also worth noting that ToolYour supports the Model Context Protocol (MCP) for agent integrations with platforms like Cursor and Claude. While this guide focuses on the REST API, MCP allows agents to discover and invoke ToolYour tools using a similar underlying API. If you are building agentic workflows, you might interact with the /mcp endpoint and send goals, e.g., {"goal": "Convert this document to PDF", "input": {"file_url": "https://yoursite.com/report.docx"}}. It's important to know that solve_task via MCP is currently in an early phase. Routing, workflows, and tool coverage are improving regularly. You might frequently encounter status: suggest responses. For production-critical agentic flows, it's currently recommended to use the discover_tools, get_tool_schema, and invoke_tool sequence for more explicit control. Learn more about MCP at https://www.toolyour.com/developers/mcp.

Handling responses and errors

After making an API call, properly handling the response is crucial for building resilient applications. This involves checking for successful operations, parsing the data, and gracefully managing any errors that occur.

A successful ToolYour API call will typically return an HTTP 200 OK status code along with a JSON body containing the result of the tool's operation. Non-2xx status codes indicate an error.

const TOOLYOUR_API_KEY = process.env.TOOLYOUR_API_KEY;

async function handleApiResponse(toolId, inputData) {
    const apiUrl = `https://api.toolyour.com/v1/tools/${toolId}`;

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Api-Key': TOOLYOUR_API_KEY,
            },
            body: JSON.stringify(inputData),
        });

        if (response.ok) {
            // Request was successful (HTTP status 200-299)
            const result = await response.json();
            console.log('Tool output:', result);
            return result;
        } else {
            // Request failed (HTTP status 4xx or 5xx)
            const errorBody = await response.json(); // API errors usually return JSON
            console.error(`ToolYour API Error: Status ${response.status} - ${response.statusText}`);
            console.error('Error details:', errorBody);

            // You can implement specific error handling based on errorBody.code or errorBody.message
            if (response.status === 401) {
                throw new Error('Authentication failed. Check your API key.');
            } else if (response.status === 400) {
                throw new Error(`Invalid request: ${errorBody.message || 'Malformed input'}`);
            } else if (response.status === 429) {
                throw new Error('Rate limit exceeded. Implement retry logic.');
            } else if (response.status === 500) {
                throw new Error('Internal server error at ToolYour. Please try again later.');
            } else {
                throw new Error(`Unexpected API error: ${errorBody.message || 'Unknown error'}`);
            }
        }
    } catch (networkError) {
        console.error('Network or unexpected error during API call:', networkError);
        throw new Error(`Failed to connect to ToolYour API: ${networkError.message}`);
    }
}

// Example: Simulating a call
const mockToolId = 'text-stats';
const mockInput = { text: 'Hello world, this is a test.' };

/*
handleApiResponse(mockToolId, mockInput)
    .then(data => console.log('Processed data:', data))
    .catch(error => console.error('Error in processing:', error.message));
*/

For a comprehensive list of error codes and their meanings, refer to the ToolYour developer documentation on errors at https://www.toolyour.com/developers/docs/errors. Understanding these errors helps you provide better feedback to your users and implement more robust error recovery mechanisms.

Quota-aware retries

ToolYour enforces certain usage limits to ensure fair access and stability of the platform. For the free plan, you are allowed 500 successful requests per month, with a rate limit of 5 successful requests per minute. It's important to build your integration with these limits in mind, especially for critical operations.

When you exceed the rate limit (5 requests per minute) or your monthly quota (500 requests per month), the API will respond with an HTTP 429 Too Many Requests status code. In such cases, your plan caps further requests until you upgrade your plan or until the next calendar month (quota resets on the 1st of each month). ToolYour does not use an "overage" or "pay-as-you-go" billing model. Notably, invalid requests that fail due to malformed input or authentication issues generally do not count against your quota.

Implementing a retry mechanism with exponential backoff for 429 errors is a best practice. This pattern attempts to resend the request after waiting for an increasing amount of time, reducing the load on the API and increasing the chance of success as the rate limit window passes.

const TOOLYOUR_API_KEY = process.env.TOOLYOUR_API_KEY;

// Helper function for delays
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function invokeToolWithRetries(toolId, inputData, retries = 3) {
    const apiUrl = `https://api.toolyour.com/v1/tools/${toolId}`;
    let attempts = 0;
    const maxAttempts = retries + 1; // Initial attempt + retries

    while (attempts < maxAttempts) {
        attempts++;
        try {
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Api-Key': TOOLYOUR_API_KEY,
                },
                body: JSON.stringify(inputData),
            });

            if (response.ok) {
                console.log(`Attempt ${attempts}: Request successful.`);
                const result = await response.json();
                return result;
            } else if (response.status === 429 && attempts < maxAttempts) {
                const retryAfter = response.headers.get('Retry-After'); // Check if API suggests a retry time
                const delayMs = retryAfter ? parseInt(retryAfter) * 1000 : Math.pow(2, attempts - 1) * 1000; // Exponential backoff or header suggestion
                console.warn(`Attempt ${attempts}: Rate limit hit (429). Retrying in ${delayMs / 1000} seconds...`);
                await delay(delayMs);
            } else {
                const errorBody = await response.json();
                console.error(`Attempt ${attempts}: API Error (${response.status}):`, errorBody);
                throw new Error(`ToolYour API request failed: ${response.status} - ${errorBody.message || response.statusText}`);
            }
        } catch (error) {
            console.error(`Attempt ${attempts}: Network or unexpected error:`, error.message);
            if (attempts >= maxAttempts) {
                throw new Error(`Failed after ${maxAttempts} attempts: ${error.message}`);
            }
            // For network errors, we can also implement a small delay before next attempt
            await delay(1000 * attempts); // Simple delay for network issues
        }
    }
    throw new Error('Exceeded maximum retry attempts.');
}

// Example usage:
// const toolIdForRetry = 'digital-tools/page-speed-analyzer'; // Placeholder
// const inputForRetry = { url: 'https://yoursite.com/my-page' };

/*
invokeToolWithRetries(toolIdForRetry, inputForRetry)
    .then(result => console.log('Final success:', result))
    .catch(error => console.error('Final failure:', error));
*/

Monitoring your usage is also important. You can track your current quota consumption from your ToolYour dashboard at https://www.toolyour.com/dashboard/api-keys. For details on different plans and their respective limits, visit https://www.toolyour.com/pricing or https://www.toolyour.com/developers/docs/usage-and-plans.

FAQ

What are the limits for the ToolYour free plan?

The ToolYour free plan allows for 500 successful requests per month and a rate limit of 5 successful requests per minute. These limits are shared across both the REST API and Model Context Protocol (MCP) usage.

Do I need separate API keys for the REST API and Model Context Protocol (MCP)?

No, a single API key from your ToolYour account works for both the REST API and MCP. All API keys under one account share the same monthly quota.

What happens if I exceed my monthly quota or rate limit?

If you exceed your monthly quota or the per-minute rate limit, ToolYour will block further requests by returning an HTTP 429 Too Many Requests status code. Your requests will be capped until you upgrade your plan or until your quota resets on the 1st of the next calendar month. ToolYour does not charge for overages.

Do failed API requests count against my quota?

Generally, only successful tool calls count towards your monthly quota. Invalid requests, such as those with incorrect authentication or malformed input, typically do not consume your quota.

How often does my ToolYour API quota reset?

Your monthly quota for ToolYour API requests resets on the 1st of each calendar month.

Can I use ToolYour tools in my browser for free without signing up?

Yes, many ToolYour tools are available for free use directly in your browser without requiring a signup or an API key. This is separate from the API usage. You can explore them at https://www.toolyour.com/.

What is solve_task in MCP, and is it ready for production?

solve_task is an MCP endpoint that allows agents to describe a goal and input, letting ToolYour route the request to the appropriate tool or workflow. It is currently in an early phase, with routing, workflows, and tool coverage continually improving. You may frequently receive a status: suggest response. For production-critical agentic flows, it's recommended to use the sequence of discover_tools, get_tool_schema, and invoke_tool for more explicit control over tool selection and execution.

Conclusion

Integrating the ToolYour API into your Node.js application enables you to leverage a powerful suite of digital utilities with a streamlined, developer-friendly experience. By following this setup guide, Node.js backend developers can confidently implement authentication, make structured API calls, and build robust error handling and quota-aware retry mechanisms.

The ToolYour API Node.js integration empowers your product with capabilities like document conversion, SEO analysis, and various AI utilities, without the need to build them from scratch. Remember to protect your API keys, handle responses diligently, and consider the API's usage limits for a smooth and scalable integration.

Ready to enhance your application with ToolYour?

  • Explore the full range of tools and detailed API documentation at https://www.toolyour.com/developers/docs.
  • Manage your API keys and monitor your usage from your dashboard at https://www.toolyour.com/dashboard/api-keys.
  • Review available plans and pricing options to scale your integration at https://www.toolyour.com/pricing.