Mastering API Request Output Handling in Dify: A Comprehensive Guide
As an open-source intelligent agent development platform, Dify excels at integrating various Application Programming Interfaces (APIs) to extend the capabilities of artificial intelligence (AI) applications. Whether you’re invoking third-party Large Language Model (LLM) APIs, data service APIs, or custom backend APIs, the final step in the workflow – processing the API request output – directly determines the quality of the application’s experience.
Many developers encounter frustrations when using Dify: API responses return unstructured JSON data that cannot be directly displayed to users; the output format is incompatible with subsequent nodes (such as LLMs or notification nodes); or APIs occasionally return errors that cause the entire workflow to crash. These issues all point to a core requirement: mastering the correct methods for handling API request outputs in Dify.

This comprehensive guide will systematically answer the question: “How to handle request outputs from APIs in Dify?” We’ll begin with the fundamentals of API output parsing, then delve into three core handling methods (template conversion, code execution, direct response configuration), and finally, through practical examples and advanced skills, help you comprehensively master the essentials of Dify API output handling. By the end of this article, you’ll be able to flexibly handle any API output and build stable, efficient Dify workflows.
Prerequisites: Understanding Common Formats of Dify API Request Outputs
Before processing API outputs, it’s crucial to understand the common output formats returned by APIs in Dify. Different formats require different processing strategies. The most common types include:
1. JSON Format (Most Common)
Most APIs (such as LLM APIs and data query APIs) return data in JSON format. For example, a response from a text generation API might look like this:
{
"code": 200,
"data": {
"result": "This is the generated text content.",
"task_id": "task-123456",
"execution_time": 1.2
},
"message": "success"
}
In Dify’s HTTP Request node, you can directly access nested fields using variable syntax (e.g., {{http_request_node.data.result}}). However, complex JSON structures (such as arrays with multiple elements) require further parsing.
2. Text/Markdown Format
Some APIs return content in plain text or Markdown format (e.g., documentation APIs, note service APIs). This type of output is relatively easy to handle but may require formatting adjustments (such as line breaks, bold text) to improve readability.
3. File/Link Format
Multimedia-related APIs (such as image generation APIs and file storage APIs) often return file URLs or Base64 encoded strings. For example, the output of an image generation API might contain a url field pointing to the generated image, which needs to be converted into a displayable format (such as a Markdown image link) for easy user presentation.
4. Error Response Format
When an API call fails, it typically returns an error response (e.g., {"code": 500, "message": "Server error"} or {"error": "Invalid API key"}). Correctly handling error outputs is crucial to ensure that the workflow doesn’t crash unexpectedly and to provide clear prompts to users.
Three Core Methods for Handling API Request Outputs in Dify
Dify offers several built-in nodes to handle API request outputs, suitable for different scenarios. Below, we’ll detail the three most commonly used methods, including their applicable scenarios, configuration steps, and code examples.
Method 1: Template Conversion Node (No-Code, Suitable for Simple Formats)
The Template Conversion node is based on the Jinja2 template engine and allows developers to perform lightweight data formatting, variable splicing, and structured output without writing code. It’s ideal for simple scenarios such as organizing JSON data into Markdown reports or splicing multiple fields into complete text.
Applicable Scenarios
- Converting structured JSON data into user-friendly Markdown text.
- Splicing multiple API output fields (e.g., title + content + author) into a single text.
- Adding conditional logic to display different content based on the API output (e.g., displaying success/error messages).
Step-by-Step Configuration
Let’s take handling the output of a knowledge retrieval API as an example (returning a list of knowledge chunks containing titles, content, and similarity scores):
1. Add an HTTP Request node in the Dify workflow, configure API parameters (request method, URL, headers, etc.) to call the knowledge retrieval API.
2. Add a Template Conversion node after the HTTP Request node, and select the output of the HTTP Request node as the input source.
3. Write a Jinja2 template in the Template Conversion node to format the data. For example:
## Knowledge Retrieval Results
{% if http_request.data.retrieved_chunks and http_request.data.retrieved_chunks | length > 0 %}
{% for chunk in http_request.data.retrieved_chunks %}
### {{ loop.index }}. {{ chunk.title }} (Similarity: {{ "%.2f" | format(chunk.score | default(0)) }})
{{ chunk.content | replace('\n', '\n\n') }}
---
{% endfor %}
{% else %}
No relevant information found.
{% endif %}
4. Save the configuration and test the workflow. The Template Conversion node will output a formatted Markdown report that can be directly passed to a Direct Response node for user display.
Key Jinja2 Syntax Tips
{{variable}}: Outputs the value of a variable (e.g.,{{chunk.title}}).{% for item in list %}: Iterates through an array (e.g., iterating through a list of knowledge chunks).{% if condition %}: Conditional judgment (e.g., checking if the retrieval result is empty).- Filters: Use
|to apply filters (e.g.,|lengthto get the array length,|default(0)to set a default value).
Method 2: Code Execution Node (Flexible, Suitable for Complex Processing)
When facing complex API output processing scenarios (such as parsing nested JSON arrays, converting file formats, or handling exceptions), the Code Execution node (which supports Python) is the best choice. It provides maximum flexibility, allowing you to write custom code based on specific business logic to handle API outputs.
Applicable Scenarios
- Parsing complex nested JSON data and extracting key fields.
- Handling multimedia API outputs (e.g., converting image URLs into displayable Markdown links).
- Performing data validation and cleaning (e.g., removing invalid characters, correcting data formats).
- Handling API error responses and returning user-friendly prompts.
Practical Example: Handling Image Generation API Output
Suppose we’re calling an image generation API (e.g., Jiemeng 4.0) in Dify. The API returns a JSON array containing multiple image URLs. We need to extract these URLs and convert them into Markdown image links for display. The steps are as follows:
1. Configure the HTTP Request node to call the image generation API. Use Dify’s variable syntax in the request body to pass user prompts and model parameters:
{
"model": "{{ start_node.pmodel }}",
"prompt": "{{ start_node.prompt }}",
"negativePrompt": "",
"width": 1536,
"height": 864
}
2. Add a Code Execution node, set the input parameter to the output of the HTTP Request node (named arg1), and write the following Python code to parse the image URLs:
def main(arg1: str) -> dict:
import json
# Parse JSON data returned by the API
try:
data = json.loads(arg1)
except json.JSONDecodeError:
return {"result": "Error: Invalid JSON format returned by the API."}
# Check if the data structure is correct
if not isinstance(data, dict) or 'data' not in data:
return {"result": "Error: The API output format is incorrect (missing 'data' field)."}
image_data = data.get('data', [])
if not isinstance(image_data, list):
return {"result": "Error: The 'data' field is not a valid array."}
# Traverse the image data and generate Markdown links
markdown_result = ""
for index, item in enumerate(image_data, start=1):
if not isinstance(item, dict) or 'url' not in item:
markdown_result += f"Image {index}: Failed to extract URL (missing 'url' field)\n\n"
continue
image_url = item['url']
markdown_result += f"\n\n"
return {"result": markdown_result}
3. Connect the Code Execution node to a Direct Response node and set the output of the Code Execution node (i.e., {{code_execution_node.result}}) as the response content. When the workflow runs, the user will see a formatted image preview.
Key Code Writing Tips
- Always add exception handling (e.g.,
try-exceptblocks) to avoid workflow crashes due to invalid API outputs. - Use clear error messages to help users and developers quickly locate problems.
- For large-scale data processing, pay attention to code efficiency (e.g., avoid nested loops for large arrays).
Method 3: Direct Response Configuration (Simple, Suitable for Direct Display)
If the API returns clean, user-friendly data (such as simple text or a single JSON field), you can directly configure the Direct Response node to display the API output without additional processing. This method is the simplest and most efficient, suitable for scenarios that don’t require complex formatting.
Applicable Scenarios
- The API returns a single text result (e.g., a translation API returning translated text).
- Only a specific field in the API output needs to be displayed (e.g., only displaying the
resultfield of an LLM API output). - Quickly testing API outputs during workflow debugging.
Step-by-Step Configuration
1. Complete the configuration of the HTTP Request node and test it to ensure the API returns the correct data.
2. Add a Direct Response node and select “Text” or “Markdown” for the response type.
3. Use Dify’s variable selection tool to select the API output field you need to display. For example, if the API returns {"result": "Hello World"}, you can directly enter {{http_request_node.result}} in the response content.
4. Save and test the workflow. The Direct Response node will directly display the selected API output field to the user.
Advanced Skills: Error Handling and Workflow Optimization
To build robust Dify workflows, handling API output errors and optimizing processing logic are essential. Here are some key advanced skills to help you improve workflow stability and user experience.
Comprehensive API Error Handling
APIs may return errors due to network issues, invalid parameters, or server failures. You need to handle these errors in your workflows to avoid confusing users. The implementation method is as follows:
1. Add a Condition branch node after the HTTP Request node to determine the API return status.
2. Set the judgment condition (using Jinja2 syntax). For example, check if the API returns a success status code: {{http_request_node.code == 200 and http_request_node.message == "success"}}
3. If the condition is met (the API call is successful), enter the normal processing branch (Template Conversion or Code Execution node).
4. If the condition is not met (the API call fails), enter the error handling branch: Add a Direct Response node to return a user-friendly error message, such as: API call failed. Error message: {{http_request_node.message}}. Please try again later or check your parameters.
Handling Large-Scale API Outputs
When the API returns a large amount of data (e.g., a list containing hundreds of elements), directly processing it in a single node may lead to performance issues. You can use Dify’s Iteration node to process the data in batches:
1. Add an Iteration node after the HTTP Request node, and select the large-scale array in the API output as the iteration object.
2. Add a Template Conversion or Code Execution node inside the Iteration node to process a single element in the array (e.g., extract key fields from each data item).
3. Add an aggregation node after the Iteration node to collect the processed results and splice them into a complete output.
Integrating Proxy Services for Stable API Calls
When calling APIs that are geographically restricted or have strict rate limits, unstable API calls may result in abnormal outputs. You can integrate a clientless proxy service such as IPFLY into your Dify workflow to improve stability: Configure IPFLY’s proxy parameters (IP, port, username, password) in Dify’s environment variables for easy management and reuse. In the HTTP Request node, enable proxy settings and select the IPFLY proxy parameters from the environment variables. IPFLY’s 99.99% uptime and global node coverage can effectively avoid IP bans and network latency issues, ensuring stable API outputs.
New to proxies and unsure how to choose a strategy or service? Don’t worry! First, visit IPFLY.net to learn about the basic service information, then join the IPFLY Telegram community for beginner guides and FAQs to help you get started with proxies correctly and easily!

Common Pitfalls and Solutions in Dify API Output Handling
Developers often encounter some common pitfalls when handling API request outputs in Dify. Below, we summarize these pitfalls and provide targeted solutions:
Pitfall 1: Unable to Access Nested Fields in the API Output
Symptoms: When accessing nested fields using {{http_request_node.data.result}}, the output is empty or an error is reported.
Solution: First, use the “Test” function of the HTTP Request node to check the complete API output structure and confirm that the field path is correct. If the field may be empty, use the default filter to set a default value (e.g., {{http_request_node.data.result | default("No result")}}). For dynamically changing fields, use conditional judgment to avoid accessing non-existent fields (e.g., {% if http_request_node.data %}{{ http_request_node.data.result }}{% endif %}).
Pitfall 2: API Output Contains Special Characters That Cause Display Errors
Symptoms: The API returns text containing line breaks, special symbols, or HTML tags, which are displayed abnormally in the Direct Response node.
Solution: Use the replace filter to handle line breaks (e.g., {{content | replace('\n', '\n\n')}} converts line breaks to Markdown line breaks). For HTML tags, use the striptags filter to remove them (e.g., {{content | striptags}}). For special symbols (e.g., <, >), use the safe filter to render them correctly (e.g., {{content | safe}}).
Pitfall 3: Code Execution Node Reports “Module Not Found” Error
Symptoms: When importing a third-party module (such as requests) in the Code Execution node, the error “ModuleNotFoundError” is reported.
Solution: Dify’s Code Execution node has built-in common modules (such as json, datetime), but it doesn’t support custom third-party modules. If you need to use third-party functionality (such as HTTP requests), replace it with Dify’s built-in HTTP Request node instead of importing modules in the Code Execution node. For complex functions that cannot be replaced, consider deploying a custom backend service and calling it through the HTTP Request node, handling the output in Dify.
Practical Example: Building a Complete API Output Handling Workflow in Dify
To help you integrate the knowledge you’ve learned above, we’ll build a complete workflow: call a product information API, process the output (parse JSON data, format it into Markdown), handle errors, and finally display the results to the user.
Workflow Overview
Start Node (receive user input: product ID) → HTTP Request Node (call product information API) → Condition Branch Node (determine if API call is successful) → Normal Branch (Template Conversion Node: format product data) → Error Branch (Direct Response Node: return error message) → Direct Response Node (display formatted product information).
Key Node Configuration
1. Start Node: Add a text input field named product_id to receive the user’s input product ID.
2. HTTP Request Node:
Request Method: GET
Request URL: https://api.example.com/product?product_id={{start_node.product_id}}
Headers: Add an Authorization header (if needed) to verify the API call.
3. Condition Branch Node:
Judgment Condition: {{http_request_node.code == 200 and http_request_node.data.success}}
4. Template Conversion Node (Normal Branch):
## Product Information
- Product ID: {{http_request_node.data.product.id}}
- Product Name: {{http_request_node.data.product.name}}
- Price: ${{http_request_node.data.product.price | format("%.2f")}}
- Stock Status: {% if http_request_node.data.product.stock > 0 %}In stock ({{http_request_node.data.product.stock}} units remaining){% else %}Out of stock{% endif %}
- Description: {{http_request_node.data.product.description | replace('\n', '\n\n')}}
5. Direct Response Node (Error Branch):
Content: Failed to retrieve product information. Error: {{http_request_node.data.error_message}}. Please check if the product ID is correct.
6. Direct Response Node (Final Display):
Content: {{template_conversion_node.result}}
After configuring the workflow, test it with a valid product ID. You’ll see the formatted product information; if you enter an invalid product ID, the workflow will return a clear error message.
Master API Output Handling to Build Powerful Dify Applications
Handling API request outputs is a critical link in Dify workflow development. By mastering the three core methods (template conversion, code execution, direct response configuration) and advanced skills such as error handling and large-scale data processing, you can transform raw API responses into user-friendly, usable data and build stable, efficient AI applications.
Remember to choose the appropriate processing method based on the complexity of the API output and business requirements: use direct response for simple scenarios, template conversion for no-code formatting, and code execution for complex processing. At the same time, be careful to avoid common pitfalls and use debugging tools to ensure the workflow runs smoothly.
If you’re ready to practice, try building the product information workflow in a practical example. Through continuous practice, you’ll be able to flexibly handle any API output in Dify and fully leverage the platform’s capabilities!