Documentation: Using Direct Line API in a React Native Application with Axios

This document details the usage of the Microsoft Direct Line API in a React Native application, using JavaScript, Axios, and WebSocket for communication with a Copilot Agent Bot.

Pre-requisites

Before proceeding, ensure the following are…


This content originally appeared on DEV Community and was authored by Vivek Yadav

This document details the usage of the Microsoft Direct Line API in a React Native application, using JavaScript, Axios, and WebSocket for communication with a Copilot Agent Bot.

Pre-requisites

Before proceeding, ensure the following are in place:

1. Direct Line Secret: Obtain the Direct Line secret from the Coilot chat Bot.

2. React Native Development Environment: Set up a working React Native project.

3. Axios Library Installed: Add Axios to your project dependencies using npm install axios or yarn add axios.

4. WebSocket Support: Ensure the WebSocket API is compatible with your application environment.

5. Basic Knowledge: Familiarity with JavaScript, React Native, and RESTful APIs.

Table of Contents

  1. Authentication

  2. Generating Token

  3. Refreshing the Token

  4. Starting the Conversation

  5. Reconnecting the Conversation

  6. Sending Activity to the Bot

  7. Receiving Activity from the Bot

  8. Ending the Conversation

  9. Connection Status Monitoring and Reconnection

  10. References

1. Authentication

Direct Line API requires a secret to authenticate. Obtain the secret from the Azure Bot Service portal.

2. Generating Token

Tokens are generated using the secret to initiate secure communication.

Code Example:

import axios from 'axios';

const generateToken = async (secret) => {
    const url = 'https://directline.botframework.com/v3/directline/tokens/generate';
    try {
        const response = await axios.post(url, {}, {
            headers: {
                Authorization: `Bearer ${secret}`,
            },
        });
        return response.data.token;
    } catch (error) {
        console.error('Error generating token:', error);
        throw error;
    }
};

3. Refreshing the Token

Tokens have a limited lifespan. Refresh them before they expire.

Code Example:

const refreshToken = async (token) => {
    const url = 'https://directline.botframework.com/v3/directline/tokens/refresh';
    try {
        const response = await axios.post(url, {}, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
        return response.data.token;
    } catch (error) {
        console.error('Error refreshing token:', error);
        throw error;
    }
};

4. Starting the Conversation

Initiate a conversation with the bot using the token.

Code Example:

const startConversation = async (token) => {
    const url = 'https://directline.botframework.com/v3/directline/conversations';
    try {
        const response = await axios.post(url, {}, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
        return response.data;
    } catch (error) {
        console.error('Error starting conversation:', error);
        throw error;
    }
};

5. Reconnecting the Conversation

If the connection is lost, you can reconnect using the conversationId and WebSocket.

Code Example:

const reconnectConversation = async (conversationId, token) => {
    const url = `https://directline.botframework.com/v3/directline/conversations/${conversationId}?watermark=0`;
    try {
        const response = await axios.get(url, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
        return response.data;
    } catch (error) {
        console.error('Error reconnecting conversation:', error);
        throw error;
    }
};

6. Sending Activity to the Bot

Send user messages or activities to the bot.

Code Example:

const sendActivity = async (conversationId, token, activity) => {
    const url = `https://directline.botframework.com/v3/directline/conversations/${conversationId}/activities`;
    try {
        const response = await axios.post(url, activity, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
        return response.data;
    } catch (error) {
        console.error('Error sending activity:', error);
        throw error;
    }
};

7. Receiving Activity from the Bot

Use WebSocket to listen for bot responses in real time.

Code Example:

const connectWebSocket = (streamUrl, onMessage) => {
    const socket = new WebSocket(streamUrl);

    socket.onopen = () => {
        console.log('WebSocket connection established.');
    };

    socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        console.log('Message received:', data);
        onMessage(data.activities);
    };

    socket.onerror = (error) => {
        console.error('WebSocket error:', error);
    };

    socket.onclose = (event) => {
        console.warn('WebSocket connection closed:', event);
    };

    return socket;
};

8. Ending the Conversation

Explicitly end a conversation by ceasing communication.

Note: Direct Line API doesn’t require an explicit API call to "end" a conversation.

9. Connection Status Monitoring and Reconnection

Monitor WebSocket status, and fallback to polling if disconnected.

Code Example:

const monitorConnection = (socket, fallbackToPolling) => {
    socket.onclose = () => {
        console.warn('WebSocket connection closed. Falling back to polling.');
        fallbackToPolling();
    };
};

const pollForActivities = async (conversationId, token) => {
    const url = `https://directline.botframework.com/v3/directline/conversations/${conversationId}/activities`;
    try {
        const response = await axios.get(url, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
        return response.data.activities;
    } catch (error) {
        console.error('Error polling for activities:', error);
        throw error;
    }
};

10. References

Conclusion

This document provides a complete guide to integrate Direct Line API into a React Native application using Axios and WebSocket. Follow the outlined steps to authenticate, manage conversations, and handle communication reliably with a Copilot Agent Bot.


This content originally appeared on DEV Community and was authored by Vivek Yadav


Print Share Comment Cite Upload Translate Updates
APA

Vivek Yadav | Sciencx (2025-01-14T04:40:07+00:00) Documentation: Using Direct Line API in a React Native Application with Axios. Retrieved from https://www.scien.cx/2025/01/14/documentation-using-direct-line-api-in-a-react-native-application-with-axios/

MLA
" » Documentation: Using Direct Line API in a React Native Application with Axios." Vivek Yadav | Sciencx - Tuesday January 14, 2025, https://www.scien.cx/2025/01/14/documentation-using-direct-line-api-in-a-react-native-application-with-axios/
HARVARD
Vivek Yadav | Sciencx Tuesday January 14, 2025 » Documentation: Using Direct Line API in a React Native Application with Axios., viewed ,<https://www.scien.cx/2025/01/14/documentation-using-direct-line-api-in-a-react-native-application-with-axios/>
VANCOUVER
Vivek Yadav | Sciencx - » Documentation: Using Direct Line API in a React Native Application with Axios. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/14/documentation-using-direct-line-api-in-a-react-native-application-with-axios/
CHICAGO
" » Documentation: Using Direct Line API in a React Native Application with Axios." Vivek Yadav | Sciencx - Accessed . https://www.scien.cx/2025/01/14/documentation-using-direct-line-api-in-a-react-native-application-with-axios/
IEEE
" » Documentation: Using Direct Line API in a React Native Application with Axios." Vivek Yadav | Sciencx [Online]. Available: https://www.scien.cx/2025/01/14/documentation-using-direct-line-api-in-a-react-native-application-with-axios/. [Accessed: ]
rf:citation
» Documentation: Using Direct Line API in a React Native Application with Axios | Vivek Yadav | Sciencx | https://www.scien.cx/2025/01/14/documentation-using-direct-line-api-in-a-react-native-application-with-axios/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.