Skip to main content

API Request Tool

The API Request tool allows your agents to interact with any REST API endpoint. It provides complete control over HTTP methods, headers, request bodies, and response handling.
This tool has Default status, meaning it’s production-ready and available on all subscription plans.

Overview

The API Request tool is one of the most versatile tools in PLai Framework, enabling agents to:

Connect to APIs

Integrate with any REST API service or endpoint

Custom Headers

Configure authentication, content types, and custom headers

Flexible Methods

Support for GET, POST, PATCH, DELETE, and LIST HTTP methods

Template System

Dynamic URL and body templating with variable substitution

Configuration Parameters

url_template
input
required
The API endpoint URL with optional template variables
Example: https://api.example.com/users/{{user_id: str}}/profile
Variables: Use {{variable_name: type}} syntax (types: str, int, float, bool)
method
input
required
HTTP method for the request
Supported methods: GET, POST, PATCH, DELETE, LIST
Note: This parameter is required (no default value)
headers_template
string
required
HTTP headers as a JSON string with optional template variables
Example: "{\"Authorization\": \"Bearer {{api_token: str}}\", \"User-Agent\": \"PLai-Agent/1.0\"}"
Default: "{}"
Note: Must be a JSON string, not an object
content_type
select
Content type for request body
Options:
  • application/json - For JSON payloads (default)
  • application/x-www-form-urlencoded - For form data
    Default: application/json
body_template
string
required
Request body as a JSON string or form-encoded string with template variables
Example (JSON): "{\"name\": {{user_name: str}}, \"email\": {{user_email: str}}}"
Example (Form): "username={{username: str}}&password={{password: str}}"
Default: "{}"
Note: Must be a string. For JSON, system adds quotes automatically for str types

Setup Instructions

1

Navigate to Tools

Go to the Tools section in your project dashboard
2

Create API Request Tool

Click Create Tool and select API Request (type: HTTP)
3

Configure URL

Enter the API endpoint URL in the URL Template field
4

Set HTTP Method

Specify the HTTP method (GET, POST, PATCH, DELETE, or LIST) in the Method field
5

Configure Headers

Add required headers including authentication in Headers Template (default: "{}")
6

Set Content Type (Optional)

Choose the appropriate content type for your API (default: application/json)
7

Configure Body

Configure the Body Template (default: "{}")
8

Test Configuration

Use the test button to verify your configuration works
9

Add to Agent

Assign this tool to your agents in agent settings
Required Parameters: name, description, method, url_template, body_template, headers_templateOptional Parameters: content_type (defaults to application/json)

Usage Examples

Basic GET Request

{
  "url_template": "https://jsonplaceholder.typicode.com/posts/{{post_id: str}}",
  "method": "GET",
  "headers_template": "{\"Accept\": \"application/json\", \"User-Agent\": \"PLai-Agent/1.0\"}",
  "content_type": "application/json",
  "body_template": "{}"
}

Authenticated API Call

{
  "url_template": "https://api.github.com/user/repos",
  "method": "GET",
  "headers_template": "{\"Authorization\": \"Bearer {{github_token: str}}\", \"Accept\": \"application/vnd.github.v3+json\"}",
  "content_type": "application/json",
  "body_template": "{}"
}

POST Request with Data

{
  "url_template": "https://api.example.com/users",
  "method": "POST",
  "headers_template": "{\"Authorization\": \"Bearer {{api_token: str}}\", \"Content-Type\": \"application/json\"}",
  "content_type": "application/json",
  "body_template": "{\"name\": {{user_name: str}}, \"email\": {{user_email: str}}, \"role\": \"user\"}"
}

CRM Integration (Salesforce)

{
  "url_template": "https://{{instance: str}}.salesforce.com/services/data/v57.0/sobjects/Contact",
  "method": "POST",
  "headers_template": "{\"Authorization\": \"Bearer {{sf_access_token: str}}\", \"Content-Type\": \"application/json\"}",
  "content_type": "application/json",
  "body_template": "{\"FirstName\": {{first_name: str}}, \"LastName\": {{last_name: str}}, \"Email\": {{email: str}}, \"Phone\": {{phone: str}}}"
}

Common Use Cases

Customer Relationship Management (CRM)

  • Create/update leads and contacts
  • Retrieve customer information
  • Update opportunity status
  • Sync customer data

Payment Processing

  • Process payments
  • Manage customer subscriptions
  • Handle refunds
  • Retrieve transaction history

Communication Services

  • Send messages to channels
  • Create private conversations
  • Post file attachments
  • Manage workspace users

Template Variables

Variable Substitution

The API Request tool uses a typed variable system with the format {{variable_name: type}}:
{
  "url_template": "https://api.example.com/users/{{user_id: str}}/orders/{{order_id: str}}",
  "body_template": "{\"status\": {{new_status: str}}, \"updated_by\": {{agent_name: str}}, \"timestamp\": {{current_time: str}}}"
}

Supported Variable Types

str

String values - text, IDs, names, etc.

int

Integer numbers - counts, IDs, quantities

float

Decimal numbers - prices, percentages, measurements

bool

Boolean values - true/false flags
Important Rules:
  • ✅ Always include the type: {{variable: str}}
  • ✅ Templates must be JSON strings, not objects
  • ✅ For str types in JSON, quotes are added automatically
  • ✅ All templates are required: url_template, body_template, headers_template

Variable Type Examples

{
  "url_template": "https://api.example.com/users/{{user_id: int}}/posts/{{post_id: str}}",
  "body_template": "{\"active\": {{is_active: bool}}, \"score\": {{rating: float}}, \"name\": {{username: str}}}"
}

Available Variables

Variables are provided by the agent during execution:
  • User-provided: Variables from chat context or form inputs
  • System variables: Current time, agent name, user ID, etc.
  • Previous responses: Data from earlier tool calls in the conversation
  • Context variables: Information from the current conversation

Real-World Examples

GET Request with URL Parameters

{
  "method": "GET",
  "url_template": "https://timeapi.io/api/time/current/zone?timeZone=Europe/{{city: str}}",
  "headers_template": "{}",
  "body_template": "{}",
  "content_type": "application/json"
}
Use Case: Query time zone information for different European cities dynamically.

POST Request with JSON Body

{
  "method": "POST",
  "url_template": "https://api.example.com/data",
  "headers_template": "{\"Content-Type\": \"application/json\", \"Authorization\": \"Bearer {{token: str}}\"}",
  "body_template": "{\"key\": {{value: str}}, \"count\": {{count: int}}, \"active\": {{active: bool}}}",
  "content_type": "application/json"
}
Use Case: Send structured data to an API with mixed data types.

POST Request with Form-Encoded Data

{
  "method": "POST",
  "url_template": "https://api.example.com/login",
  "headers_template": "{\"X-API-Key\": \"test-key\"}",
  "body_template": "username={{username: str}}&password={{password: str}}&remember={{remember: bool}}",
  "content_type": "application/x-www-form-urlencoded"
}
Use Case: Submit traditional HTML form data with authentication.

Response Handling

Response Processing

The API Request tool processes API responses and returns them as strings:
  1. Status Code Validation: Automatically validates HTTP status codes using raise_for_status()
  2. JSON Parsing: Attempts to parse JSON responses
  3. String Conversion: Returns response data as a string representation
  4. Error Handling: Returns error messages as strings when requests fail

Response Format

Responses are returned as strings, not structured objects.
Successful JSON Response:
"{'id': 123, 'name': 'John Doe', 'email': 'john@example.com'}"
Successful Non-JSON Response:
"Request successful"
Error Response:
"Error message describing what went wrong"
The agent will receive the response as a string and can extract information from it. The response includes the actual API data when JSON parsing is successful, or a success message when the response body cannot be parsed as JSON.

Error Handling

Error Response Behavior

When an API request fails, the tool returns an error message as a string. All errors are caught and returned as descriptive text messages.

Common Error Scenarios

Cause: Invalid or expired API keys, insufficient permissionsError Message Example:
"401 Client Error: Unauthorized for url: https://api.example.com/users"
Solutions:
  • Verify API key is correct and active
  • Check permission scopes for the API key
  • Ensure proper header format for authentication
  • Confirm the API endpoint supports your authentication method
Cause: Exceeded API rate limitsError Message Example:
"429 Client Error: Too Many Requests for url: https://api.example.com/users"
Solutions:
  • Reduce request frequency
  • Wait before retrying the request
  • Upgrade API plan if available
Cause: Invalid request format or missing required fieldsError Message Example:
"400 Client Error: Bad Request for url: https://api.example.com/users"
Solutions:
  • Validate request body against API documentation
  • Check required fields are included
  • Verify data types match API expectations
  • Test with API documentation examples
Cause: Connection issues, DNS failures, or timeoutError Message Example:
"ConnectionError: Failed to establish a new connection"
Solutions:
  • Check network connectivity
  • Verify the API endpoint URL is correct
  • Check if the API service is operational
  • Ensure firewall rules allow the connection
All errors are logged and returned as string messages. The tool uses basic error handling provided by the requests library, with automatic status code validation via raise_for_status().

Security Best Practices

API Key Security: Never hardcode API keys in templates. Use secure variable substitution instead.

Secure Configuration

{
  "headers_template": "{\"Authorization\": \"Bearer {{secure_api_token: str}}\", \"X-API-Key\": \"{{api_key: str}}\"}"
}
Remember that headers_template must be a JSON string, not an object.

Security Features

The API Request tool provides basic security through the underlying HTTP libraries:
  • HTTPS Support: ✅ Fully supported for secure connections
  • SSL Certificate Validation: ✅ Enabled by default via the requests library
  • Secure Headers: ✅ Support for Authorization headers and API keys via templates

Security Checklist

  • Use HTTPS: Always use secure HTTPS endpoints
  • Variable Substitution: Use template variables for sensitive data like API keys
  • Minimal Permissions: Use API keys with minimal required permissions
  • Rotate Keys: Regularly rotate API keys and tokens
  • Monitor Usage: Track API usage patterns in your application

Troubleshooting

Testing Your Configuration

Use these approaches to test your API Request tool configuration:
  1. API Testing Tools: Test your endpoint with Postman, Insomnia, or curl first
  2. Verify JSON Format: Ensure headers_template and body_template are valid JSON strings
  3. Check Variable Types: Verify all template variables have correct type annotations
  4. Test Incrementally: Start with simple GET requests before adding complex bodies
  5. Review Responses: Check the string response returned by the tool for debugging

Common Issues

Cause: Invalid JSON in headers_template or body_templateSolution: Ensure templates are valid JSON strings with proper escaping:
"{\"key\": \"value\"}"  // Correct
{"key": "value"}         // Incorrect (object, not string)
Cause: Template variable not provided during executionSolution: Ensure all variables in templates are available from the agent context
Cause: Variable value cannot be converted to specified typeSolution: Verify the data type matches the template variable type:
  • {{count: int}} requires integer value
  • {{active: bool}} requires boolean value

Next Steps