Dify How to Handle Request Output from API: Step-by-Step Configuration & Code Examples

16 Views

As an open-source intelligent agent development platform, Dify excels at integrating various APIs to extend the capabilities of AI applications. Whether you’re calling a third-party LLM API, a data service API, or a custom backend API, the final step of the workflow—handling the API request output—directly determines the quality of the application experience.

Many developers encounter frustrations when working with Dify: the API returns unstructured JSON data that can’t be directly displayed to users; the output format is incompatible with subsequent nodes (such as LLM or notification nodes); or the API occasionally returns errors that cause the entire workflow to crash. These issues all point to a core requirement: mastering the correct methods to handle API request output in Dify.

Dify How to Handle Request Output from API: Step-by-Step Configuration & Code Examples

This guide will systematically answer the question “how to handle request output from API in Dify”. We’ll start from the basics of API output parsing, then dive into three core handling methods (Template Conversion, Code Execution, Direct Response Configuration), and finally through practical cases and advanced skills, help you fully grasp the key points of Dify API output handling. By the end of this article, you’ll be able to flexibly process any API output and build stable, efficient Dify workflows.

Prerequisite: Understand the Common Formats of Dify API Request Output

Before handling API output, it’s crucial to clarify the common output formats returned by APIs in Dify. Different formats require different handling strategies. The most common types are:

1. JSON Format (Most Common)

Most APIs (such as LLM APIs, data query APIs) return JSON-formatted data. For example, the 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 through variable syntax (e.g., {{ http_request_node.data.result }}), but complex JSON structures (such as arrays with multiple elements) require further parsing.

2. Text/Markdown Format

Some APIs return plain text or Markdown-formatted content (e.g., documentation APIs, note-taking service APIs). This type of output is relatively easy to handle, but may need formatting adjustments (such as line breaks, bolding) to improve readability.

3. File/Link Format

Multimedia-related APIs (such as image generation APIs, 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 Markdown image links) for user-friendly presentation.

4. Error Response Format

When an API call fails, it usually returns an error response (e.g., {"code": 500, "message": "Server error"} or {"error": "Invalid API key"}). Proper handling of error outputs is essential to ensure the workflow doesn’t crash unexpectedly and can provide clear prompts to users.

Three Core Methods to Handle API Request Output in Dify

Dify provides multiple 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 Formatting)

The Template Conversion node is based on the Jinja2 template engine, allowing 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 a complete text.

Applicable Scenarios

  • Convert structured JSON data into user-friendly Markdown text
  • Splice multiple API output fields (e.g., title + content + author) into a single text
  • Add conditional logic to display different content based on API output (e.g., show success/error messages)

Step-by-Step Configuration

Take the example of processing the output of a knowledge retrieval API (returning a list of knowledge chunks with titles, content, and similarity scores):

1.Add an HTTP Request node in the Dify workflow and configure the 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, which can be directly passed to the Direct Response node for user display.

Key Jinja2 Syntax Tips

  • {{ variable }}: Output the value of a variable (e.g., {{ chunk.title }}).
  • {% for item in list %}: Loop through an array (e.g., traverse the list of knowledge chunks).
  • {% if condition %}: Conditional judgment (e.g., check if the retrieval result is empty).
  • Filters: Use | to apply filters (e.g., | length gets the array length, | default(0) sets 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 (supporting Python) is the best choice. It provides maximum flexibility, allowing you to write custom code to process API outputs according to specific business logic.

Applicable Scenarios

  • Parse complex nested JSON data and extract key fields
  • Process multimedia API outputs (e.g., convert image URLs into displayable Markdown links)
  • Perform data verification and cleaning (e.g., remove invalid characters, correct data formats)
  • Handle API error responses and return user-friendly prompts

Practical Case: Processing Image Generation API Output

Suppose we call an image generation API (such as Jimeng 4.0) in Dify, and 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. The request body uses Dify’s variable syntax 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 as 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"![Generated Image {index}]({image_url})\n\n"
    
    return {"result": markdown_result}

3.Connect the Code Execution node to the 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, users will see formatted image previews.

Key Code Writing Tips

  • Always add exception handling (such as try-except blocks) to avoid workflow crashes due to invalid API output.
  • Use clear error messages to help users and developers locate problems quickly.
  • 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 where no complex formatting is required.

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., displaying only the result field of the LLM API output).
  • Quickly test the API output during workflow debugging.

Step-by-Step Configuration

1.Complete the configuration of the HTTP Request node and test to ensure the API returns the correct data.

2.Add a Direct Response node, and select “Text” or “Markdown” as the response type.

3.Use Dify’s variable selection tool to select the API output field that needs to be displayed. 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 & Workflow Optimization

To build a robust Dify workflow, handling API output errors and optimizing the processing logic are essential. Below are key advanced skills to help you improve the stability and user experience of your workflow.

Comprehensive API Error Handling

APIs may return errors due to network issues, invalid parameters, or server failures. You need to handle these errors in the workflow to avoid confusing users. The implementation method is as follows:

1.Add a Condition Branch node after the HTTP Request node to judge the API return status.

2.Set the judgment condition (using Jinja2 syntax). For example, check if the API returns a successful status code: {{ http_request_node.code == 200 and http_request_node.message == "success" }}

3.If the condition is met (API call successful), enter the normal processing branch (Template Conversion or Code Execution node).

4.If the condition is not met (API call failed), 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 Output

When the API returns a large amount of data (such as a list with hundreds of elements), directly processing it in a single node may cause 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., extracting key fields of 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 geo-restricted or have strict rate limits, unstable API calls may lead to abnormal output. You can integrate a client-free proxy service like IPFLY into the 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 the proxy setting 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 output.

New to proxies and unsure how to choose strategies or services? Don’t stress! First visit IPFLY.net for basic service info, then join the IPFLY Telegram community—get beginner guides and FAQs to help you use proxies right, easy start!

Dify How to Handle Request Output from API: Step-by-Step Configuration & Code Examples

Common Pitfalls & Solutions in Dify API Output Handling

During the process of handling API request output in Dify, developers often encounter some common pitfalls. Below we summarize these pitfalls and provide targeted solutions:

Pitfall 1: Unable to Access Nested Fields in API Output

Symptom: When using {{ http_request_node.data.result }} to access nested fields, 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 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 'result' in http_request_node.data %}{{ http_request_node.data.result }}{% endif %}).

Pitfall 2: API Output Contains Special Characters Causing Display Errors

Symptom: 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 process line breaks (e.g., {{ content | replace('\n', '\n\n') }} converts line breaks to Markdown line breaks).For HTML tags, use thestriptags filter to remove them (e.g., {{ content | striptags }}).For special symbols (such as <, >), use the safe filter to render them correctly (e.g., {{ content | safe }}).

Pitfall 3: Code Execution Node Reports “Module Not Found” Error

Symptom: When importing third-party modules (such as requests) in the Code Execution node, an error “ModuleNotFoundError” is reported. Solution: Dify’s Code Execution node has built-in common modules (such as json, datetime), but does not support custom third-party modules.If you need to use third-party functions (such as HTTP requests), replace them with Dify’s built-in HTTP Request node instead of importing modules in the Code Execution node.For complex functions that can’t be replaced, consider deploying a custom backend service, calling it via the HTTP Request node, and processing the output in Dify.

Practical Case: Build a Complete API Output Handling Workflow in Dify

To help you integrate the knowledge 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 result to the user.

Workflow Overview

Start Node (Receive User Input: Product ID) → HTTP Request Node (Call Product Information API) → Condition Branch Node (Judge API Call Success) → 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 product ID entered by the user.

2.HTTP Request Node:

Request Method: GET

Request URL: https://api.example.com/product?product_id={{ start_node.product_id }}

Headers: Add Authorization header (if needed) to authenticate 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 left){% 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 get 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 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 output is a key 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 convert raw API responses into user-friendly, usable data and build stable, efficient AI applications.

Remember to choose the appropriate handling method according to the complexity of the API output and business needs: use Direct Response for simple scenarios, Template Conversion for no-code formatting, and Code Execution for complex processing. At the same time, pay attention to avoiding 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 the practical case. With continuous practice, you’ll be able to flexibly handle any API output in Dify and give full play to the platform’s capabilities!

END
 0