dify-spring-boot-starter
  • Guide
  • Getting-started
  • Install
  • Configure
  • Client Builder
  • Features

    • Chat API
    • Workflow API
    • Dataset API
    • Server API
  • Event

    • Instructions
    • Chat event
  • Using configurations
  • Customized Configuration
  • v1.x-SNAPSHOT
  • v0.x
  • Changelog
  • 简体中文
  • English
GitHub
  • Guide
  • Getting-started
  • Install
  • Configure
  • Client Builder
  • Features

    • Chat API
    • Workflow API
    • Dataset API
    • Server API
  • Event

    • Instructions
    • Chat event
  • Using configurations
  • Customized Configuration
  • v1.x-SNAPSHOT
  • v0.x
  • Changelog
  • 简体中文
  • English
GitHub
  • Guide

    • Guide
    • Getting-started
    • Install
    • Configure
    • Client Builder
  • Features

    • Chat API
    • Workflow API
    • Dataset API
    • Server API
  • Event

    • Instructions
    • Chat event

Chat API

Interface Overview

Chat service interfaces provide complete chat functionality integration capabilities, including message sending and receiving, session management, voice conversion and other core functions. All interfaces require a valid API key for authentication. Use the DifyChat interface instance.

1. Message

1.1 Send a message

Method

ChatMessageSendResponse send(ChatMessageSendRequest sendRequest);

Request Parameters

ChatMessageSendRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesUser id
conversationIdStringNoChat session number
contentStringYesMessage content
filesList<ChatMessageFile>Nofile
inputsMap<String, Object>NoCustomized parameters

ChatMessageFile Structure:

Parameter nameTypeDescription
idStringFile ID
typeStringFile type, default is "image"
urlStringPreview image URL
transferMethodStringTransfer method, default is "remote_url"
belongsToStringFile owner, user or assistant
uploadFileIdStringUpload file ID

Response parameter

ChatMessageSendResponse

Parameter nameTypeDescription
conversationIdStringChat session number
messageIdStringMessage id
createdAtLongCreating timestamps
taskIdStringTask id
idStringid
answerStringanswer

1.2 Send Streaming Messages

Method

Flux<ChatMessageSendCompletionResponse> sendChatMessageStream(ChatMessageSendRequest sendRequest);

Request Parameters

Same as the Send Message interface

Response parameter

Returns a message stream with the following structure:

ChatMessageSendCompletionResponse

Parameter nameTypeDescription
workflowRunIdStringWorkflow run ID
dataCompletionDataCompletion data, varies by event type

The CompletionData structure varies depending on the event type:

Event TypeDescriptionCorresponding Data Class
workflow_startedWorkflow startedWorkflowStartedData
node_startedNode startedNodeStartedData
node_finishedNode finishedNodeFinishedData
workflow_finishedWorkflow finishedWorkflowFinishedData

1.3 Termination message flow

Method

void stopMessagesStream(String apiKey, String taskId, String userId);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
taskIdStringYestaskId
userIdStringYesuserId

1.4 Message Feedback

Method

MessageFeedbackResponse messageFeedback(MessageFeedbackRequest messageFeedbackRequest);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesuserId
messageIdStringYesmessageId
ratingRatingYesrating
contentStringYesMessage Feedback Specific Information

Response parameter

MessageFeedbackResponse

Parameter nameTypeDescription
resultStringFixed return success

1.5 Getting a list of messages

Method

DifyPageResult<MessagesResponseVO> messages(MessagesRequest request);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesuserId
conversationIdStringYesChat session number
firstIdStringNoFirst record id
limitIntegerNoNumber of records per page, default 20条

Response parameter

Parameter nameTypeDescription
idStringMessage ID
conversationIdStringConversation ID
inputsMap<String, Object>User input parameters
queryStringUser input/question content
messageFilesList<MessageFile>Message files
answerStringAnswer message content
createdAtLongCreation timestamp
feedbackFeedbackFeedback information

MessageFile Structure:

Parameter nameTypeDescription
idStringFile ID
filenameStringFile name
typeStringFile type, e.g., "image"
urlStringPreview image URL
mimeTypeStringFile MIME type
sizeLongFile size in bytes
transferMethodStringTransfer method
belongsToStringFile owner, "user" or "assistant"
uploadFileIdStringUpload file ID
agentThoughtsList<MessageFileAgentThought>Agent thoughts (not empty only in Agent mode)

MessageFileAgentThought Structure:

Parameter nameTypeDescription
idStringagent_thought ID, each Agent iteration has a unique id
messageIdStringMessage unique ID
positionIntegeragent_thought position in the message, e.g., position 1 for the first iteration
thoughtStringAgent's thought content
observationStringTool call result
toolStringList of tools used, separated by ;
toolInputStringTool input, JSON formatted string (object). E.g.: {"dalle3": {"prompt": "a cute cat"}}
createdAtLongCreation timestamp, e.g.: 1705395332
messageFilesList<String>File IDs associated with the current agent_thought
conversationIdStringConversation ID

Feedback Structure:

Parameter nameTypeDescription
ratingStringlike/dislike rating

1.6 Get Suggested Responses

Method

List<String> messagesSuggested(String messageId, String apiKey, String userId);

Request Parameters

Parameter nameTypeRequiredDescription
messageIdStringYesmessageId
apiKeyStringYesapiKey
userIdStringYesuserId

Response parameter

Return to the list of suggested response texts

1.7 Get Application Feedback List

Method

DifyPageResult<AppFeedbackResponse> feedbacks(AppFeedbackPageRequest request);

Request Parameters

AppFeedbackPageRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesUser id
pageIntegerNoPage number, default 1
limitIntegerNoRecords per page, default 20, range 1-100

Response Parameters

AppFeedbackResponse

Parameter nameTypeDescription
idStringFeedback id
appIdStringApplication id
conversationIdStringConversation id
messageIdStringMessage id
ratingStringRating (like/dislike)
contentStringFeedback content
fromSourceStringSource
fromEndUserIdStringEnd user id
fromAccountIdStringAccount id
createdAtLocalDateTimeCreation timestamp
updatedAtLocalDateTimeUpdate timestamp

1.8 Get Conversation Variables

Method

DifyPageResult<ConversationVariableResponse> conversationVariables(ConversationVariableRequest request);

Request Parameters

ConversationVariableRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesUser id
conversationIdStringYesConversation id
variableNameStringNoVariable name, return all if not empty

Response Parameters

ConversationVariableResponse

Parameter nameTypeDescription
idStringVariable id
nameStringVariable name
valueTypeStringValue type (string/json)
valueStringVariable value
descriptionStringDescription
createdAtLongCreation timestamp (timestamp)
updatedAtLongUpdate timestamp (timestamp)

1.9 Update Conversation Variable

Method

ConversationVariableResponse updateConversationVariable(UpdateConversationVariableRequest request);

Request Parameters

UpdateConversationVariableRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesUser id
conversationIdStringYesConversation id
variableIdStringYesVariable id
valueStringYesNew variable value

Response Parameters

ConversationVariableResponse

Parameter nameTypeDescription
idStringVariable id
nameStringVariable name
valueTypeStringValue type (string/json)
valueStringVariable value
descriptionStringDescription
createdAtLongCreation timestamp (timestamp)
updatedAtLongUpdate timestamp (timestamp)

2. Session

2.1 Get session list

Method

DifyPageResult<MessageConversationsResponse> conversations(MessageConversationsRequest request);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesuserId
lastIdStringNoLast record id
limitIntegerNoNumber of records per page, default 20
sortByStringNoSort field, default -updated_at

Response parameter

MessageConversationsResponse

Parameter nameTypeDescription
idStringChat session number
nameStringSession name
inputsMap<String,Object>Input parameter
statusStringSession state
introductionStringOpening remarks
createdAtLongCreating timestamps
updatedAtLongUpdating timestamps

2.2 Deleting a session

Method

void deleteConversation(String conversationId, String apiKey, String userId);

Request Parameters

Parameter nameTypeRequiredDescription
conversationIdStringYesChat session number
apiKeyStringYesapiKey
userIdStringYesuserId

2.3 Session rename

Method

MessageConversationsResponse renameConversation(RenameConversationRequest renameConversationRequest);

Request Parameters

Parameter nameTypeRequiredDescription
conversationIdStringYesChat session number
nameStringYesSession name
autoGenerateStringNoAuto-generated title, default false
apiKeyStringYesapiKey
userIdStringYesuserId

Response parameter

MessageConversationsResponse

Parameter nameTypeDescription
idStringChat session number
nameStringSession name
inputsMap<String,Object>Input parameter
statusStringSession state
introductionStringOpening remarks
createdAtLongCreating timestamps
updatedAtLongUpdating timestamps

3. Other

3.1 text-to-speech

Method

ResponseEntity<byte[]> textToAudio(TextToAudioRequest request);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesuserId
textStringYesConvert Text
messageIdStringNomessageId

Response parameter

Returns an audio file stream

Usage example

import java.io.IOException;

private void textToAudio(TextToAudioRequest request, HttpServletResponse response) {
    try {
        ResponseEntity<byte[]> responseEntity = difyChat.textToAudio(request);

        String type = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        response.setContentType(type != null ? type : "audio/mpeg");

        String contentDisposition = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
        if (contentDisposition != null) {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        } else {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=audio.mp3");
        }

        if (responseEntity.getBody() != null) {
            response.getOutputStream().write(responseEntity.getBody());
            response.getOutputStream().flush();
        }

    } catch (Exception e) {
        log.error("textToAudio error: {}", e.getMessage());
        throw new RuntimeException("textToAudio error");
    }
}

3.2 speech-to-text

Method

DifyTextVO audioToText(AudioToTextRequest request);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesuserId
fileMultipartFileYesAudio file

Response parameter

Parameter nameTypeDescription
textStringConvert Text

3.3 Get Application Parameters

Method

AppParametersResponseVO parameters(String apiKey);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey

Response Parameters

AppParametersResponseVO

Parameter nameTypeDescription
openingStatementStringOpening statement
suggestedQuestionsList<String>Opening recommended questions
suggestedQuestionsAfterAnswerEnabledEnable recommended questions after answer
speechToTextEnabledSpeech-to-text feature config
textToSpeechTextToSpeechText-to-speech feature config
retrieverResourceEnabledReference and attribution config
annotationReplyEnabledAnnotation reply config
moreLikeThisEnabledMore like this feature config
userInputFormList<UserInputForm>User input form config
sensitiveWordAvoidanceEnabledSensitive word avoidance config
fileUploadFileUploadFile upload config
systemParametersFileUploadConfigSystem parameters config

Enabled Object Structure:

Parameter nameTypeDescription
enabledBooleanWhether enabled

TextToSpeech Object Structure:

Parameter nameTypeDescription
enabledBooleanWhether enabled
voiceStringVoice type

FileUpload Object Structure:

Parameter nameTypeDescription
enabledBooleanWhether file upload is enabled
imageFileUploadImageImage upload configuration
allowedFileTypesList<String> Allowed file types list
allowedFileExtensionsList<String>Allowed file extensions list
allowedFileUploadMethodsList<String>Allowed upload methods list
numberLimitsIntegerFile count limit
fileUploadConfigFileUploadConfigDetailed upload configuration

FileUploadImage Object Structure:

Parameter nameTypeDescription
enabledBooleanWhether image upload is enabled
numberLimitsIntegerImage count limit, default 3
transferMethodsList<String>Transfer methods: remote_url, local_file

FileUploadConfig Object Structure:

Parameter nameTypeDescription
fileSizeLimitIntegerFile size limit (MB)
batchCountLimitIntegerBatch upload count limit
imageFileSizeLimitIntegerImage file size limit (MB)
videoFileSizeLimitIntegerVideo file size limit (MB)
audioFileSizeLimitIntegerAudio file size limit (MB)
workflowFileUploadLimitIntegerWorkflow file upload limit

UserInputForm Object Structure:

Parameter nameTypeDescription
textInputTextInputText input control config
paragraphParagraphParagraph text input config
selectSelectDropdown control config

TextInput Object Structure:

Parameter nameTypeDescription
labelStringControl display label
variableStringControl ID
requiredBooleanWhether required
maxLengthIntegerMaximum length limit
defaultValueStringDefault value

Paragraph Object Structure: Inherits from TextInput, has the same field structure

Select Object Structure:

Parameter nameTypeDescription
labelStringControl display label
variableStringControl ID
requiredBooleanWhether required
maxLengthIntegerMaximum length limit
defaultValueStringDefault value
typeStringDropdown type
optionsList<String>Options list

3.4 File Upload

Method

FileUploadResponse fileUpload(FileUploadRequest request);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesuserId
fileMultipartFileYesFile to upload

Response Parameters

FileUploadResponse

Parameter nameTypeDescription
idStringFile id
nameStringFile name
sizeIntegerFile size (bytes)
extensionStringFile extension
mimeTypeStringFile MIME type
createdByStringCreator
createdAtLongCreation timestamp

3.5 Get Application Info

Method

AppInfoResponse info(String apiKey);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey

Response Parameters

AppInfoResponse

Parameter nameTypeDescription
nameStringApplication name
descriptionStringApplication description
tagsList<String>Application tags list

3.6 Get Application Metadata

Method

AppMetaResponse meta(String apiKey);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey

Response Parameters

AppMetaResponse

Parameter nameTypeDescription
toolIconsMap<String, Object>Tool icons mapping

3.7 Get Application WebApp Settings

Method

AppSiteResponse site(String apikey);

Request Parameters

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey

Response Parameters

AppSiteResponse

Parameter nameTypeDescription
titleStringWebApp name
chatColorThemeStringChat color theme, in hex format
chatColorThemeInvertedBooleanWhether the chat color theme is inverted
iconTypeIconTypeEnumIcon type, emoji - emoji, image - picture
iconStringIcon. If it's emoji type, it's an emoji symbol; if it's image type, it's an image URL
iconBackgroundStringBackground color in hex format
iconUrlStringIcon URL
descriptionStringDescription
copyrightStringCopyright information
privacyPolicyStringPrivacy policy link
customDisclaimerStringCustom disclaimer
defaultLanguageStringDefault language
showWorkflowStepsBooleanWhether to show workflow details
useIconAsAnswerIconBooleanWhether to replace 🤖 in chat with the WebApp icon

3.8 File preview

Method

ResponseEntity<byte[]> filePreview(FilePreviewRequest request);

Request Parameters

FilePreviewRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesuserId
fileIdStringYesUnique identifier of the file to preview, obtained from file upload API response
asAttachmentBooleanNoWhether to force the file to be downloaded as an attachment. Default is false (preview in browser)

Response Parameters

Returns file content with appropriate headers for browser display or download.

Response Headers
  • Content-Type: Set according to file MIME type
  • Content-Length: File size in bytes (if available)
  • Content-Disposition: Set to "attachment" if asAttachment=true
  • Cache-Control: Cache headers for performance
  • Accept-Ranges: Set to "bytes" for audio/video files

Usage Examples

Basic Usage
// Create file preview request
FilePreviewRequest request = new FilePreviewRequest("file-id-123")
                .setApiKey("your-api-key")
                .setUserId("user-123");

// Execute file preview
ResponseEntity<byte[]> response = difyChat.filePreview(request);

// Get file content
byte[] fileContent = response.getBody();
Preview File (Display in Browser)
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

private void previewFile(String fileId, HttpServletResponse response) {
    try {
        FilePreviewRequest request = new FilePreviewRequest(fileId)
                .setApiKey("your-api-key")
                .setUserId("user-123")
                .setAsAttachment(false); // Preview in browser

        ResponseEntity<byte[]> responseEntity = difyChat.filePreview(request);

        // Set response headers
        String contentType = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        response.setContentType(contentType != null ? contentType : "application/octet-stream");

        String contentLength = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_LENGTH);
        if (contentLength != null) {
            response.setContentLength(Integer.parseInt(contentLength));
        }

        // Copy cache control headers
        String cacheControl = responseEntity.getHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
        if (cacheControl != null) {
            response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControl);
        }

        // Write file content
        if (responseEntity.getBody() != null) {
            response.getOutputStream().write(responseEntity.getBody());
            response.getOutputStream().flush();
        }

    } catch (Exception e) {
        log.error("File preview error: {}", e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Download File (As Attachment)
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

private void downloadFile(String fileId, String filename, HttpServletResponse response) {
    try {
        FilePreviewRequest request = new FilePreviewRequest(fileId, true, "your-api-key", "user-123");

        ResponseEntity<byte[]> responseEntity = difyChat.filePreview(request);

        // Set response headers
        String contentType = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        response.setContentType(contentType != null ? contentType : "application/octet-stream");

        String contentDisposition = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
        if (contentDisposition != null) {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        } else {
            // Set custom filename
            String safeFilename = filename != null ? filename : "download";
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + safeFilename + "\"");
        }

        // Write file content
        if (responseEntity.getBody() != null) {
            response.getOutputStream().write(responseEntity.getBody());
            response.getOutputStream().flush();
        }

    } catch (Exception e) {
        log.error("File download error: {}", e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

4. Application Annotation

required Dify version 1.2.0 or higher

4.1 Get Application Annotations List

Method

DifyPageResult<AppAnnotationResponse> pageAppAnnotation(AppAnnotationPageRequest request);

Request Parameters

AppAnnotationPageRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesUser id
pageIntegerNoPage number, default 1
limitIntegerNoRecords per page, default 20, range 1-100

Response Parameters

AppAnnotationResponse

Parameter nameTypeDescription
idStringAnnotation id
questionStringQuestion content
answerStringAnswer content
hitCountIntegerHit count
createdAtLongCreation timestamp

4.2 Create Application Annotation

Method

AppAnnotationResponse createAppAnnotation(AppAnnotationCreateRequest request);

Request Parameters

AppAnnotationCreateRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesUser id
questionStringYesQuestion content
answerStringYesAnswer content

Response Parameters

AppAnnotationResponse

Parameter nameTypeDescription
idStringAnnotation id
questionStringQuestion content
answerStringAnswer content
hitCountIntegerHit count
createdAtLongCreation timestamp

4.3 Update Application Annotation

required Dify version 1.3.1 or higher

Method

AppAnnotationResponse updateAppAnnotation(AppAnnotationUpdateRequest request);

Request Parameters

AppAnnotationUpdateRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesapiKey
userIdStringYesUser id
annotationIdStringYesAnnotation id
questionStringYesQuestion content
answerStringYesAnswer content

Response Parameters

AppAnnotationResponse

Parameter nameTypeDescription
idStringAnnotation id
questionStringQuestion content
answerStringAnswer content
hitCountIntegerHit count
createdAtLongCreation timestamp

4.4 Delete Application Annotation

Method

void deleteAppAnnotation(String annotationId, String apiKey);

Request Parameters

Parameter nameTypeRequiredDescription
annotationIdStringYesAnnotation id
apiKeyStringYesapiKey

Response Parameters

not have

4.5 Annotation Reply

Method

AppAnnotationReplyResponse annotationReply(AppAnnotationReplyRequest request);

Request Parameters

AppAnnotationReplyRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesAPI key
userIdStringYesUser ID
actionAnnotationReplyActionEnumYesReply action type
embeddingProviderNameStringNoEmbedding model provider
embeddingModelNameStringNoEmbedding model name
scoreThresholdFloatNoScore threshold

AnnotationReplyActionEnum values:

  • enable - Enable annotation reply
  • disable - Disable annotation reply

Response Parameters

AppAnnotationReplyResponse

Parameter nameTypeDescription
jobIdStringJob ID
jobStatusStringJob status
errorMsgStringError message

4.6 Query Annotation Reply Status

Method

AppAnnotationReplyResponse queryAnnotationReply(AppAnnotationReplyQueryRequest request);

Request Parameters

AppAnnotationReplyQueryRequest

Parameter nameTypeRequiredDescription
apiKeyStringYesAPI key
userIdStringYesUser ID
actionAnnotationReplyActionEnumYesReply action type
jobIdStringYesJob ID to query

Response Parameters

AppAnnotationReplyResponse

Parameter nameTypeDescription
jobIdStringJob ID
jobStatusStringJob status
errorMsgStringError message
Edit this page on GitHub
Last Updated: 9/8/25, 8:06 AM
Next
Workflow API