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 11, 2026
5 min read
Article

Integrate ToolYour API in Python

Author

Abdul Wahab Raza

Founder, ToolYour

Integrate ToolYour API in Python

ToolYour is a versatile platform offering a comprehensive catalog of 200+ utilities for individuals, applications, and AI agents. Whether you're enhancing a web application, automating internal scripts, or integrating powerful tools into an AI workflow, ToolYour provides a unified interface through its REST API and Model Context Protocol (MCP).

This guide focuses on integrating the ToolYour API into your Python applications, providing a step-by-step approach from prerequisites and secure API key management to making your first successful API call using the requests library. You’ll learn how to handle responses, manage errors, and understand your quota, enabling you to effectively leverage the ToolYour API in Python.

For developers integrating ToolYour into a Node.js environment, refer to our Integrate ToolYour API in Node.js guide. For an in-depth understanding of authentication mechanisms across all ToolYour APIs, consult the ToolYour REST API Authentication Guide.

Prerequisites

Before you can begin integrating the ToolYour API in Python, ensure you have the following:

  • Python Environment: You need a working Python 3.x installation. Most modern systems come with Python pre-installed. You can verify your installation by running python --version or python3 --version in your terminal.
  • requests Library: This popular HTTP library simplifies making web requests in Python. Install it using pip:
    pip install requests python-dotenv
    
    We also include python-dotenv for securely managing environment variables, which is covered in the next section.
  • ToolYour Account and API Key: To access the ToolYour API, you need an API key linked to your ToolYour account.
    1. If you don't have an account, sign up for free at https://www.toolyour.com/signup.
    2. Once logged in, navigate to your API keys dashboard at https://www.toolyour.com/dashboard/api-keys to generate a new API key. Your API key will start with the prefix ty_.
  • Understanding Your Plan: ToolYour offers a free plan that provides 500 successful API requests per month, shared across both REST API and MCP usage. This free plan also includes a throughput limit of 5 successful requests per minute. Your quota resets on the 1st of each calendar month. For details on available plans and their limits, visit https://www.toolyour.com/pricing.

Store API keys safely

Protecting your API key is paramount to preventing unauthorized access and usage of your ToolYour account. Never hardcode your API key directly into your application's source code, especially if the code will be committed to a version control system.

The recommended best practice is to store your API key as an environment variable. This method keeps sensitive information out of your codebase and allows for easy configuration changes across different deployment environments.

Here's how to use python-dotenv to manage your API key:

  1. Create a .env file: In the root directory of your Python project, create a file named .env. Add your API key to this file in the format KEY=VALUE:

    TOOLYOUR_API_KEY=ty_YOUR_ACTUAL_API_KEY_HERE
    

    Important: Replace ty_YOUR_ACTUAL_API_KEY_HERE with your actual API key from https://www.toolyour.com/dashboard/api-keys.

  2. Add .env to .gitignore: To ensure your .env file is not accidentally committed to your Git repository, add .env to your project's .gitignore file.

.gitignore

.env
```

3. Load the API key in Python: In your Python script, use os.getenv to load the API key. The python-dotenv library helps load variables from your .env file into os.environ.

```python
import os
from dotenv import load_dotenv

Load environment variables from .env file

load_dotenv()

Retrieve your API key

TOOLYOUR_API_KEY = os.getenv("TOOLYOUR_API_KEY")

if not TOOLYOUR_API_KEY:
    raise ValueError("TOOLYOUR_API_KEY not found. Please set it in your .env file or environment.")

print("API Key loaded successfully.")

In a real application, avoid printing sensitive info like API keys.

```
This setup ensures that your API key is loaded securely and is not exposed in your public code.

Example requests call

The ToolYour API allows you to access a wide range of digital tools, file converters, SEO utilities, and AI-powered services programmatically. For this example, we'll demonstrate how to use requests to interact with the ToolYour API, specifically showcasing the solve_task endpoint which leverages the Model Context Protocol (MCP) for goal-oriented tool execution. This endpoint simplifies tool invocation by allowing you to describe a goal, and ToolYour's system will attempt to find and run the appropriate tools.

For direct REST API calls involving specific tools, you would typically use discover_tools to find available tools, get_tool_schema to understand their inputs, and then invoke_tool to run them with precise parameters. The general API documentation at https://www.toolyour.com/developers/docs/calling-tools provides detailed paths and schemas for each tool.

The solve_task endpoint is an early phase feature. Its routing capabilities, workflow orchestration, and tool coverage are regularly improving. It is common for the system to respond with status: suggest, indicating that it has identified a tool but requires further confirmation or explicit invocation via discover_toolsget_tool_schemainvoke_tool for production-critical flows.

Here's a Python example using requests to call the solve_task endpoint, asking it to analyze text statistics:

import os
import requests
import json
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

TOOLYOUR_API_KEY = os.getenv("TOOLYOUR_API_KEY")
if not TOOLYOUR_API_KEY:
    raise ValueError("TOOLYOUR_API_KEY not found. Please set it in your .env file or environment.")

# Define the ToolYour API endpoint for solve_task
API_URL = "https://api.toolyour.com/mcp"

# Set up headers with your API key
headers = {
    "X-Api-Key": TOOLYOUR_API_KEY,
    "Content-Type": "application/json",
}

# Define the goal and input for solve_task

# We want to analyze text statistics for a sample text.
payload = {
    "goal": "Analyze the text provided for its statistics like word count, character count.",
    "input": {
        "text": "The quick brown fox jumps over the lazy dog. This is a sample sentence for analysis."
    }
}

print(f"Attempting to call ToolYour API at {API_URL}...")

try:

# Make the POST request
    response = requests.post(API_URL, headers=headers, json=payload)

# Check if the request was successful (HTTP status code 2xx)
    if response.ok:
        print("\nAPI call successful!")
        response_data = response.json()
        print(json.dumps(response_data, indent=2))

# Check the status of the solve_task
        if response_data.get("status") == "success":
            print("\nTask completed successfully with results:")
            if "output" in response_data:
                print(json.dumps(response_data["output"], indent=2))
        elif response_data.get("status") == "suggest":
            print("\nTask suggested a tool or action:")
            print("The `solve_task` is in an early phase. For production-critical flows, consider using `discover_tools` -> `get_tool_schema` -> `invoke_tool` based on the suggestions.")
            if "suggestions" in response_data:
                print(json.dumps(response_data["suggestions"], indent=2))
        else:
            print(f"\nTask status: {response_data.get('status', 'unknown')}. Further details may be in the response.")
            print(json.dumps(response_data, indent=2))

    else:

# Request was not successful
        print(f"\nAPI call failed with status code: {response.status_code}")
        try:
            error_details = response.json()
            print("Error details:")
            print(json.dumps(error_details, indent=2))
        except json.JSONDecodeError:
            print("No JSON error details available. Raw response content:")
            print(response.text)

except requests.exceptions.RequestException as e:
    print(f"\nAn error occurred during the API request: {e}")
except Exception as e:
    print(f"\nAn unexpected error occurred: {e}")

When you run this script, it will send a request to ToolYour with the specified goal. The response will contain information about the outcome, including any tool suggestions or direct results. If the solve_task successfully identifies and runs a text-stats tool, you might see output similar to word count, character count, etc.

For detailed information on configuring an MCP client, please refer to the dedicated ToolYour MCP documentation.

Error handling

Robust error handling is essential for any production-ready application that interacts with external APIs. The ToolYour API will respond with various HTTP status codes and JSON error payloads to indicate the outcome of your requests. Properly handling these responses ensures your application behaves predictably and gracefully in the event of issues.

Common HTTP status codes you might encounter include:

  • 2xx (Success): Indicates the request was successfully received, understood, and accepted. For example, 200 OK.
  • 4xx (Client Errors): Indicates that the client (your application) made an invalid request.
    • 400 Bad Request: The request payload was malformed or missing required parameters.
    • 401 Unauthorized: Missing or invalid X-Api-Key header.
    • 403 Forbidden: The API key has insufficient permissions, or you've hit a quota limit.
    • 404 Not Found: The requested endpoint or resource does not exist.
    • 429 Too Many Requests: You have exceeded your rate limit (e.g., 5 requests per minute on the free plan).
  • 5xx (Server Errors): Indicates that the ToolYour server encountered an error while processing a valid request.

The requests library simplifies error checking with the response.ok property and by raising HTTPError for bad responses if explicitly told to.

Here's an enhanced example of error handling based on the previous solve_task call:

import os
import requests
import json
from dotenv import load_dotenv

load_dotenv()
TOOLYOUR_API_KEY = os.getenv("TOOLYOUR_API_KEY")
if not TOOLYOUR_API_KEY:
    raise ValueError("TOOLYOUR_API_KEY not found.")

API_URL = "https://api.toolyour.com/mcp"
headers = {
    "X-Api-Key": TOOLYOUR_API_KEY,
    "Content-Type": "application/json",
}
payload = {
    "goal": "Summarize this text.",
    "input": {
        "text": "ToolYour provides a suite of online utilities ranging from file converters to advanced AI tools. Developers can integrate these tools into their applications using the REST API or the Model Context Protocol (MCP). Secure API key management is crucial for robust integration. The platform offers a free tier with specific usage limits."
    }
}

try:
    response = requests.post(API_URL, headers=headers, json=payload)
    response.raise_for_status()

# Raises an HTTPError for bad responses (4xx or 5xx)

# If no exception, then the request was successful
    response_data = response.json()
    print("API call successful!")
    print(json.dumps(response_data, indent=2))

    if response_data.get("status") == "success":
        print("\nTask completed with results:")
        if "output" in response_data:
            print(json.dumps(response_data["output"], indent=2))
    elif response_data.get("status") == "suggest":
        print("\nTask suggested a tool or action, consider manual invocation for critical flows:")
        if "suggestions" in response_data:
            print(json.dumps(response_data["suggestions"], indent=2))
    else:
        print(f"\nTask status: {response_data.get('status', 'unknown')}. Further details may be in the response.")

except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
    print(f"Status Code: {http_err.response.status_code}")
    try:
        error_details = http_err.response.json()
        print("Error details from API:")
        print(json.dumps(error_details, indent=2))
    except json.JSONDecodeError:
        print("No JSON error details. Raw response:")
        print(http_err.response.text)
except requests.exceptions.ConnectionError as conn_err:
    print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
    print(f"Request timed out: {timeout_err}")
except requests.exceptions.RequestException as req_err:
    print(f"An unexpected request error occurred: {req_err}")
except ValueError as val_err:
    print(f"Configuration error: {val_err}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

This code now uses response.raise_for_status() to automatically catch 4xx and 5xx errors, making your error handling more concise. Always refer to the ToolYour API Errors documentation for a comprehensive list of error codes and their meanings.

Quota awareness

Understanding and managing your API quota is critical for uninterrupted service. ToolYour implements clear usage policies to ensure fair access and sustainable operation.

  • Free Plan Limits: The free plan includes 500 successful API requests per calendar month. Additionally, there's a rate limit of 5 successful requests per minute.
  • What Counts Towards Quota: Only successful tool calls count against your monthly quota. Requests that fail due to client-side errors (e.g., 400 Bad Request from malformed JSON) or authentication issues (e.g., 401 Unauthorized) generally do not count.
  • Shared Quota: Your monthly quota is shared across all surfaces of ToolYour API usage. This means requests made via the REST API and calls to Model Context Protocol (MCP) endpoints (like solve_task) all draw from the same pool of 500 requests. If you have multiple API keys associated with your account, they also share this single monthly quota.
  • Quota Reset: Your monthly request quota resets automatically on the 1st day of each calendar month.
  • Exceeding Limits: If you exceed your monthly request limit or the per-minute throughput limit, further requests will be blocked. ToolYour does not offer an "overage" or "pay-as-you-go" billing model. To continue using the API beyond the free tier limits, you will need to upgrade your plan. Your access will be restored automatically at the start of the next calendar month if you remain on the free plan.

To monitor your usage and manage your subscription, visit your ToolYour dashboard. For detailed information on usage, limits, and upgrading your plan, refer to the ToolYour Usage and Plans documentation and the pricing page.

FAQ

Here are answers to common questions about integrating the ToolYour API in Python:

Q: What is ToolYour? A: ToolYour is a platform that provides over 200 digital tools and utilities. These tools are available free in the browser, and programmatically via a REST API for applications and the Model Context Protocol (MCP) for agents like Cursor and Claude. It offers a unified catalog, API key, and plan across all its surfaces.

Q: How do I get an API key for ToolYour? A: You can generate an API key by logging into your ToolYour account and navigating to the API Keys section of your dashboard. Your API key will begin with the prefix ty_.

Q: Can I use the ToolYour free plan for production applications? A: The free plan offers 500 successful requests per month and a rate limit of 5 requests per minute. While suitable for development and testing, these limits are generally insufficient for most production-critical applications. We recommend reviewing our pricing plans for options better suited for production workloads.

Q: Do calls made to the Model Context Protocol (MCP) endpoints count towards my ToolYour API quota? A: Yes, all successful tool calls, whether made through the REST API or via MCP endpoints like solve_task, contribute to your shared monthly quota. This quota is also shared across any multiple API keys associated with your account.

Q: Where can I find specific endpoints and schemas for individual tools? A: The comprehensive documentation for all ToolYour API endpoints, including tool-specific paths, request parameters, and response schemas, is available in the Calling Tools section of our developer documentation.

Q: What happens if I exceed my monthly API quota? A: If you exceed your monthly quota of 500 successful requests or the 5 requests per minute throughput limit on the free plan, subsequent API requests will be blocked. There is no "overage" billing; service will resume at the start of the next calendar month, or immediately if you upgrade your plan.

Q: The solve_task endpoint returned status: suggest. What does this mean, and can I use it for critical workflows? A: solve_task is in an early phase of development. A status: suggest response indicates that the system identified a potential tool or action but might require explicit confirmation or a more structured invocation. For production-critical flows, it's recommended to use the discover_toolsget_tool_schemainvoke_tool pattern, which provides more control and deterministic execution.

Conclusion

Integrating the ToolYour API in Python empowers your applications with a vast array of utilities, from simple text processing to complex AI operations. By following the best practices outlined in this guide—securely storing your API key, implementing robust error handling, and understanding your quota limits—you can build reliable and efficient integrations.

We've covered the essentials, including setting up your environment, making your first API call using requests and the solve_task endpoint, and preparing for common scenarios like API errors and quota limitations.

Ready to explore more?

Start building with ToolYour API in Python today and enhance your applications with powerful, accessible utilities.