Simplifying API Integration Through Clear and User-Friendly Documentation
This section provides real-world examples to demonstrate how developers can use the Real-Time Chat API in their projects.
This example shows how to authenticate, create a chat, and send a message.
Use the /auth/login
endpoint to authenticate and obtain an access token:
const axios = require('axios');
async function authenticate() {
const response = await axios.post('https://api.example.com/auth/login', {
username: 'user@example.com',
password: 'password123'
});
console.log('Access Token:', response.data.accessToken);
return response.data.accessToken;
}
Once authenticated, use the /chats/create
endpoint to create a new chat room:
async function createChat(accessToken) {
const response = await axios.post(
'https://api.example.com/chats/create',
{
name: 'Project Discussion',
participants: ['user1@example.com', 'user2@example.com']
},
{
headers: { Authorization: `Bearer ${accessToken}` }
}
);
console.log('Chat ID:', response.data.chatId);
return response.data.chatId;
}
Use the /messages/send
endpoint to send a message to the created chat:
async function sendMessage(accessToken, chatId) {
const response = await axios.post(
'https://api.example.com/messages/send',
{
chatId: chatId,
message: 'Hello, team! Let’s discuss the project here.'
},
{
headers: { Authorization: `Bearer ${accessToken}` }
}
);
console.log('Message ID:', response.data.messageId);
}
Here’s the complete flow in one script:
(async function main() {
const accessToken = await authenticate();
const chatId = await createChat(accessToken);
await sendMessage(accessToken, chatId);
})();
Retrieve messages from a specific chat using the /messages
endpoint:
async function fetchMessages(accessToken, chatId) {
const response = await axios.get('https://api.example.com/messages', {
params: { chatId: chatId, limit: 10 },
headers: { Authorization: `Bearer ${accessToken}` }
});
console.log('Messages:', response.data);
}
(async function main() {
const accessToken = await authenticate();
const chatId = 'existing-chat-id';
await fetchMessages(accessToken, chatId);
})();
These examples demonstrate how to integrate the API into a real-world project. For more detailed guidance, refer to the Endpoints Documentation.