### List Contacts using Go Source: https://docs.blooio.com/contacts/listContacts Illustrates how to list contacts using the Go programming language. This example shows how to make a GET request and handle the JSON response. ```go package main import ( "encoding/json" "fmt" "net/http" "io/ioutil" ) func main() { url := "https://backend.blooio.com/v2/api/contacts" token := "YOUR_BEARER_TOKEN" req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer " + token) client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println("Response Status:", res.Status) fmt.Println("Response Body:", string(body)) // You can then parse the JSON body into a Go struct } ``` -------------------------------- ### Make Authenticated API Request with cURL Source: https://docs.blooio.com/development Perform a simple authenticated request to the Blooio API to validate your API key. This example uses cURL and requires the BLOOIO_API_KEY environment variable to be set. ```bash curl -H "Authorization: Bearer $BLOOIO_API_KEY" \ https://backend.blooio.com/v2/api/me ``` -------------------------------- ### List Webhook Logs (Go) Source: https://docs.blooio.com/webhook-logs/listWebhookLogs Example of how to list webhook logs using Go. This code snippet demonstrates making a GET request to the Blooio API to retrieve webhook logs. ```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} req, err := http.NewRequest("GET", "https://backend.blooio.com/v2/api/webhooks/wh_abc123def456/logs", nil) if err != nil { fmt.Println(err) return } req.Header.Add("Authorization", "Bearer ") res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Send a Message via Blooio API using cURL Source: https://docs.blooio.com/development Send a message through the Blooio API using a POST request. This example demonstrates setting the Authorization header, Content-Type, an Idempotency-Key, and the JSON payload for the message text. ```bash curl -X POST "https://backend.blooio.com/v2/api/chats/%2B15551234567/messages" \ -H "Authorization: Bearer $BLOOIO_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: dev-$(uuidgen)" \ -d '{"text": "Hello from Blooio (dev)!"}' ``` -------------------------------- ### Create Webhook Source: https://docs.blooio.com/quickstart Create a webhook to receive delivery updates and inbound messages. ```APIDOC ## POST /v2/api/webhooks ### Description Registers a webhook URL to receive events such as delivery updates and inbound messages. ### Method POST ### Endpoint `https://backend.blooio.com/v2/api/webhooks` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **webhook_url** (string) - Required - The URL where webhook events will be sent. - **webhook_type** (string) - Required - The type of webhook to create (e.g., "message"). ### Request Example ```json { "webhook_url": "https://example.com/mywebhook", "webhook_type": "message" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created webhook. - **webhook_url** (string) - The registered webhook URL. - **webhook_type** (string) - The type of the registered webhook. #### Response Example ```json { "id": "whk_abcdef12345", "webhook_url": "https://example.com/mywebhook", "webhook_type": "message" } ``` ``` -------------------------------- ### Get Message Details (Go) Source: https://docs.blooio.com/messages/getMessage Example using Go to fetch message details. This code demonstrates making an HTTP GET request to the Blooio API, including the necessary Authorization header. It parses the JSON response and handles potential errors during the request or unmarshalling. ```go package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) type Message struct { MessageID string `json:"message_id"` ChatID string `json:"chat_id"` Direction string `json:"direction"` Contact struct { ContactID string `json:"contact_id"`; Name string `json:"name"`; Identifier string `json:"identifier"` } `json:"contact"` Sender string `json:"sender"` Text string `json:"text"` Attachments []map[string]interface{} `json:"attachments"` TimeSent int64 `json:"time_sent"` TimeDelivered int64 `json:"time_delivered"` Status string `json:"status"` Protocol string `json:"protocol"` Error string `json:"error"` } func getMessage(chatID, messageID, token string) (*Message, error) { url := fmt.Sprintf("https://backend.blooio.com/v2/api/chats/%s/messages/%s", chatID, messageID) client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } req.Header.Add("Authorization", "Bearer "+token) resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("failed to execute request: %w", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %w", err) } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("API request failed with status code %d: %s", resp.StatusCode, string(body)) } var message Message if err := json.Unmarshal(body, &message); err != nil { return nil, fmt.Errorf("failed to unmarshal response body: %w", err) } return &message, nil } // Example usage: // func main() { // chatID := "+15551234567" // messageID := "msg_abc123def456" // apiToken := "YOUR_BEARER_TOKEN" // // message, err := getMessage(chatID, messageID, apiToken) // if err != nil { // fmt.Println("Error:", err) // return // } // // fmt.Printf("Message Details: %+v\n", message) // } ``` -------------------------------- ### List Webhook Logs (Java) Source: https://docs.blooio.com/webhook-logs/listWebhookLogs Example of how to list webhook logs using Java. This code demonstrates making a GET request to the Blooio API to retrieve webhook logs. ```java import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.io.IOException; public class WebhookLogs { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(java.net.URI.create("https://backend.blooio.com/v2/api/webhooks/wh_abc123def456/logs")) .header("Authorization", "Bearer ") .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` -------------------------------- ### List Webhook Logs (C#) Source: https://docs.blooio.com/webhook-logs/listWebhookLogs Example of how to list webhook logs using C#. This code snippet shows how to send a GET request to the Blooio API to retrieve webhook logs. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class WebhookLogs { public static async Task GetLogsAsync() { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ""); HttpResponseMessage response = await client.GetAsync("https://backend.blooio.com/v2/api/webhooks/wh_abc123def456/logs"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` -------------------------------- ### List Webhook Logs (Python) Source: https://docs.blooio.com/webhook-logs/listWebhookLogs Example of how to list webhook logs using Python. This code snippet shows how to send a GET request to the Blooio API to fetch webhook logs. ```python import requests url = "https://backend.blooio.com/v2/api/webhooks/wh_abc123def456/logs" headers = { "Authorization": "Bearer " } response = requests.get(url, headers=headers) if response.status_code == 200: print(response.json()) else: print(f"Error: {response.status_code}") ``` -------------------------------- ### List Webhook Logs (JavaScript) Source: https://docs.blooio.com/webhook-logs/listWebhookLogs Example of how to list webhook logs using JavaScript. This code snippet demonstrates making a GET request to the Blooio API to retrieve webhook logs. ```javascript fetch('https://backend.blooio.com/v2/api/webhooks/wh_abc123def456/logs', { method: 'GET', headers: { 'Authorization': 'Bearer ' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` -------------------------------- ### List Messages in Chat (Go) Source: https://docs.blooio.com/messages/listChatMessages Example using Go's net/http package to list messages in a chat. This snippet demonstrates making an authenticated GET request and parsing the JSON response. It's suitable for backend services written in Go. ```go package main import ( "encoding/json" "fmt" "net/http" "io/ioutil" ) func listMessages(chatId string, token string) (map[string]interface{}, error) { url := fmt.Sprintf("https://backend.blooio.com/v2/api/chats/%s/messages", chatId) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer " + token) client := &http.Client{} res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } var result map[string]interface{} if err := json.Unmarshal(body, &result); err != nil { return nil, err } return result, nil } ``` -------------------------------- ### Get Message Status (C#) Source: https://docs.blooio.com/messages/getMessageStatus Example of how to retrieve the delivery status for a specific message using C#. This code uses `HttpClient` to make the GET request and handles the JSON response. ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; public class BlooioApiClient { private static readonly HttpClient client = new HttpClient(); private const string BaseUrl = "https://backend.blooio.com/v2/api"; public BlooioApiClient() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } public async Task GetMessageStatusAsync(string chatId, string messageId, string token) { // Ensure chatId is URL encoded if it contains special characters string encodedChatId = HttpUtility.UrlEncode(chatId); string requestUrl = $"{BaseUrl}/chats/{encodedChatId}/messages/{messageId}/status"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); try { HttpResponseMessage response = await client.GetAsync(requestUrl); if (!response.IsSuccessStatusCode) { string errorContent = await response.Content.ReadAsStringAsync(); throw new HttpRequestException($"API request failed with status code {response.StatusCode}: {errorContent}"); } string responseBody = await response.Content.ReadAsStringAsync(); // You might want to deserialize the JSON into a specific object instead of returning a string return responseBody; } catch (Exception ex) { Console.WriteLine($"Error fetching message status: {ex.Message}"); throw; } } // Example usage: // public static async Task Main(string[] args) // { // string token = "YOUR_API_TOKEN"; // string chatId = "+15551234567"; // or email, or group ID // string messageId = "msg_abc123def456"; // // BlooioApiClient apiClient = new BlooioApiClient(); // try // { // string status = await apiClient.GetMessageStatusAsync(chatId, messageId, token); // Console.WriteLine($"Message Status: {status}"); // } // catch (Exception ex) // { // Console.WriteLine($"An error occurred: {ex.Message}"); // } // } } ``` -------------------------------- ### Create Blooio Webhook for Message Events Source: https://docs.blooio.com/quickstart Sets up a webhook to receive delivery updates and inbound messages from Blooio. Requires an API key for authorization and specifies the webhook URL and type. ```curl curl -X POST 'https://backend.blooio.com/v2/api/webhooks' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "webhook_url": "https://example.com/mywebhook", "webhook_type": "message" }' ``` -------------------------------- ### Get Message Status (Go) Source: https://docs.blooio.com/messages/getMessageStatus Example of how to retrieve the delivery status for a specific message using Go. This code demonstrates making an HTTP GET request and handling the JSON response. ```go package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" ) func getMessageStatus(chatID string, messageID string, token string) (map[string]interface{}, error) { encodedChatID := url.QueryEscape(chatID) url := fmt.Sprintf("https://backend.blooio.com/v2/api/chats/%s/messages/%s/status", encodedChatID, messageID) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } req.Header.Set("Authorization", "Bearer "+token) client := &http.Client{} res, err := client.Do(req) if err != nil { return nil, fmt.Errorf("failed to execute request: %w", err) } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %w", err) } if res.StatusCode < 200 || res.StatusCode >= 300 { return nil, fmt.Errorf("API request failed with status code %d: %s", res.StatusCode, string(body)) } var result map[string]interface{} err = json.Unmarshal(body, &result) if err != nil { return nil, fmt.Errorf("failed to unmarshal response: %w", err) } return result, nil } // Example usage: // func main() { // token := "YOUR_API_TOKEN" // chatID := "+15551234567" // messageID := "msg_abc123def456" // // status, err := getMessageStatus(chatID, messageID, token) // if err != nil { // fmt.Println("Error:", err) // return // } // fmt.Printf("Message Status: %+v\n", status) // } ``` -------------------------------- ### Expose Local Server with ngrok Source: https://docs.blooio.com/development Use ngrok to create a public HTTPS URL for your local development server. This is necessary for Blooio to send webhooks to your local machine. ```bash ngrok http http://localhost:3001 ``` -------------------------------- ### Get Message Status (Java) Source: https://docs.blooio.com/messages/getMessageStatus Example of how to retrieve the delivery status for a specific message using Java. This code demonstrates using the `HttpClient` to perform the GET request and parse the JSON response. ```java import java.io.IOException; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import com.fasterxml.jackson.databind.ObjectMapper; public class BlooioApiClient { private static final String BASE_URL = "https://backend.blooio.com/v2/api"; private final HttpClient httpClient; private final ObjectMapper objectMapper; public BlooioApiClient() { this.httpClient = HttpClient.newHttpClient(); this.objectMapper = new ObjectMapper(); } public String getMessageStatus(String chatId, String messageId, String token) throws IOException, InterruptedException { String encodedChatId = URLEncoder.encode(chatId, StandardCharsets.UTF_8.toString()); String url = String.format("%s/chats/%s/messages/%s/status", BASE_URL, encodedChatId, messageId); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Authorization", "Bearer " + token) .GET() .build(); HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() < 200 || response.statusCode() >= 300) { throw new IOException("API request failed with status code " + response.statusCode() + ": " + response.body()); } // You might want to deserialize the JSON into a specific object instead of returning a String return response.body(); } // Example usage: // public static void main(String[] args) { // String token = "YOUR_API_TOKEN"; // String chatId = "+15551234567"; // or email, or group ID // String messageId = "msg_abc123def456"; // // BlooioApiClient client = new BlooioApiClient(); // try { // String status = client.getMessageStatus(chatId, messageId, token); // System.out.println("Message Status: " + status); // } catch (IOException | InterruptedException e) { // e.printStackTrace(); // } // } } ``` -------------------------------- ### Send Message Source: https://docs.blooio.com/quickstart Use the Messages endpoint to queue a message. The chatId is the recipient's phone number or email. ```APIDOC ## POST /v2/api/chats/{chatId}/messages ### Description Queues a message to be sent to a recipient. ### Method POST ### Endpoint `https://backend.blooio.com/v2/api/chats/{chatId}/messages` ### Parameters #### Path Parameters - **chatId** (string) - Required - The recipient's phone number or email address. #### Query Parameters None #### Request Body - **text** (string) - Required - The content of the message. ### Request Example ```json { "text": "Hello from Blooio!" } ``` ### Response #### Success Response (200) - **message_id** (string) - The unique identifier for the queued message. - **status** (string) - The status of the message, typically "queued". #### Response Example ```json { "message_id": "msg_12345abcde", "status": "queued" } ``` ``` -------------------------------- ### Get Message Status (JavaScript) Source: https://docs.blooio.com/messages/getMessageStatus Example of how to retrieve the delivery status for a specific message using JavaScript. This involves making a GET request to the Blooio API endpoint with appropriate headers for authorization. ```javascript async function getMessageStatus(chatId, messageId, token) { const url = `https://backend.blooio.com/v2/api/chats/${encodeURIComponent(chatId)}/messages/${messageId}/status`; const headers = { 'Authorization': `Bearer ${token}` }; try { const response = await fetch(url, { method: 'GET', headers: headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Error fetching message status:', error); throw error; } } // Example usage: // const token = 'YOUR_API_TOKEN'; // const chatId = '+15551234567'; // or email, or group ID // const messageId = 'msg_abc123def456'; // getMessageStatus(chatId, messageId, token) // .then(status => console.log(status)) // .catch(err => console.error(err)); ``` -------------------------------- ### Get Group Details using C# Source: https://docs.blooio.com/groups/getGroup This snippet provides a C# example for fetching group details via the Blooio API. It utilizes HttpClient to send an authenticated GET request. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class BlooioClient { public async Task GetGroupAsync(string groupId, string token) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await client.GetAsync($"https://backend.blooio.com/v2/api/groups/{groupId}"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } } ``` -------------------------------- ### Manage Webhooks Source: https://docs.blooio.com/api-reference/introduction Create, update, and delete webhooks. ```APIDOC ## PUT /v2/api/webhooks/{webhook_id} ### Description Update an existing webhook configuration. ### Method PUT ### Endpoint /v2/api/webhooks/{webhook_id} ### Parameters #### Path Parameters - **webhook_id** (string) - Required - The unique identifier of the webhook to update. #### Request Body - **url** (string) - Optional - The new URL for the webhook. - **events** (array) - Optional - A list of events to subscribe to. ### Response #### Success Response (200) - **webhook_id** (string) - The unique identifier for the webhook. - **url** (string) - The updated webhook URL. - **events** (array) - The list of subscribed events. #### Response Example ```json { "webhook_id": "wh_abcdef12345", "url": "https://yourdomain.com/new_webhook", "events": ["inbound_message"] } ``` ## DELETE /v2/api/webhooks/{webhook_id} ### Description Delete a webhook. ### Method DELETE ### Endpoint /v2/api/webhooks/{webhook_id} ### Parameters #### Path Parameters - **webhook_id** (string) - Required - The unique identifier of the webhook to delete. ### Response #### Success Response (200) - **message** (string) - Confirmation message of deletion. #### Response Example ```json { "message": "Webhook deleted successfully." } ``` ``` -------------------------------- ### Create a Blooio Webhook Subscription Source: https://docs.blooio.com/development Register a webhook endpoint with Blooio by sending a POST request to the API. This requires your public ngrok URL and your API key. ```bash curl -X POST https://backend.blooio.com/v2/api/webhooks \ -H "Authorization: Bearer $BLOOIO_API_KEY" \ -H "Content-Type: application/json" \ -d '{"webhook_url":"https://YOUR-NGROK-URL/webhooks/blooio"}' ``` -------------------------------- ### Get Group Details using Python Source: https://docs.blooio.com/groups/getGroup This snippet provides a Python example for fetching group details from the Blooio API. It uses the 'requests' library to make the authenticated GET request. ```python import requests def get_group(group_id, token): url = f"https://backend.blooio.com/v2/api/groups/{group_id}" headers = { "Authorization": f"Bearer {token}" } response = requests.get(url, headers=headers) return response.json() ``` -------------------------------- ### Get Message Status (Python) Source: https://docs.blooio.com/messages/getMessageStatus Example of how to retrieve the delivery status for a specific message using Python. This code snippet utilizes the `requests` library to make the API call. ```python import requests import urllib.parse def get_message_status(chat_id, message_id, token): encoded_chat_id = urllib.parse.quote(chat_id) url = f"https://backend.blooio.com/v2/api/chats/{encoded_chat_id}/messages/{message_id}/status" headers = { "Authorization": f"Bearer {token}" } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching message status: {e}") return None # Example usage: # token = "YOUR_API_TOKEN" # chat_id = "+15551234567" # or email, or group ID # message_id = "msg_abc123def456" # status = get_message_status(chat_id, message_id, token) # if status: # print(status) ``` -------------------------------- ### Create Webhook Subscription - Go Source: https://docs.blooio.com/webhooks/createWebhook This Go program demonstrates how to create a webhook subscription using the `net/http` package. It constructs a JSON payload with the webhook details and sends a POST request to the Blooio API. The response is then parsed into a struct. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type WebhookRequest struct { WebhookURL string `json:"webhook_url"` WebhookType string `json:"webhook_type,omitempty"` ValidUntil int64 `json:"valid_until,omitempty"` } type WebhookResponse struct { WebhookID string `json:"webhook_id"` WebhookURL string `json:"webhook_url"` Message string `json:"message,omitempty"` } func main() { url := "https://backend.blooio.com/v2/api/webhooks" payload := WebhookRequest{ WebhookURL: "https://example.com/webhook", } jsonPayload, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshaling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer ") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() var webhookResponse WebhookResponse err = json.NewDecoder(res.Body).Decode(&webhookResponse) if err != nil { fmt.Println("Error decoding response:", err) return } fmt.Printf("Webhook created: %+v\n", webhookResponse) } ``` -------------------------------- ### Send First Message using Blooio API Source: https://docs.blooio.com/quickstart Queues a message using the Blooio Messages endpoint. The chatId is the recipient's phone number or email. Requires an API key for authorization and sends a JSON payload with the message text. ```curl curl -X POST 'https://backend.blooio.com/v2/api/chats/%2B15551234567/messages' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "text": "Hello from Blooio!" }' ``` ```javascript import fetch from 'node-fetch' const chatId = encodeURIComponent('+15551234567') const res = await fetch(`https://backend.blooio.com/v2/api/chats/${chatId}/messages`, { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.BLOOIO_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello from Blooio!' }) }) const data = await res.json() ``` ```python import os, requests from urllib.parse import quote chat_id = quote('+15551234567', safe='') res = requests.post(f'https://backend.blooio.com/v2/api/chats/{chat_id}/messages', headers={ 'Authorization': f"Bearer {os.environ['BLOOIO_API_KEY']}", 'Content-Type': 'application/json' }, json={ 'text': 'Hello from Blooio!' } ) data = res.json() ``` -------------------------------- ### Get Message Status (cURL) Source: https://docs.blooio.com/messages/getMessageStatus Example of how to retrieve the delivery status for a specific message using cURL. This command requires the chat ID and message ID as path parameters. ```bash curl -X GET "https://backend.blooio.com/v2/api/chats/%2B15551234567/messages/msg_abc123def456/status" ``` -------------------------------- ### Get Message Details (C#) Source: https://docs.blooio.com/messages/getMessage Example using C# to retrieve message details. This code snippet utilizes `HttpClient` to make a GET request to the Blooio API. It demonstrates setting the Authorization header and handling the response, including error checking and reading the response content. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class BlooioApiClient { private const string BaseUrl = "https://backend.blooio.com/v2/api"; public async Task GetMessageAsync(string chatId, string messageId, string token) { using (HttpClient client = new HttpClient()) { string url = $"{BaseUrl}/chats/{chatId}/messages/{messageId}"; client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { string errorContent = await response.Content.ReadAsStringAsync(); throw new HttpRequestException($"API request failed with status code: {response.StatusCode} - {errorContent}"); } } } // Example usage: // public static async Task Main(string[] args) // { // BlooioApiClient client = new BlooioApiClient(); // string chatId = "+15551234567"; // string messageId = "msg_abc123def456"; // string apiToken = "YOUR_BEARER_TOKEN"; // // try // { // string messageDetails = await client.GetMessageAsync(chatId, messageId, apiToken); // Console.WriteLine($"Message Details: {messageDetails}"); // } // catch (HttpRequestException e) // { // Console.WriteLine($"Error: {e.Message}"); // } // } } ``` -------------------------------- ### Get Message Details (Java) Source: https://docs.blooio.com/messages/getMessage Example using Java to retrieve message details. This code snippet shows how to make an HTTP GET request using Apache HttpClient. It includes setting the Authorization header and handling the response, including potential JSON parsing errors. ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class BlooioApiClient { private static final String BASE_URL = "https://backend.blooio.com/v2/api"; public String getMessage(String chatId, String messageId, String token) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { String url = String.format("%s/chats/%s/messages/%s", BASE_URL, chatId, messageId); HttpGet request = new HttpGet(url); request.addHeader("Authorization", "Bearer " + token); try (CloseableHttpResponse response = httpClient.execute(request)) { HttpEntity entity = response.getEntity(); if (entity != null) { if (response.getStatusLine().getStatusCode() == 200) { return EntityUtils.toString(entity); } else { throw new IOException("API request failed with status code: " + response.getStatusLine().getStatusCode() + " - " + EntityUtils.toString(entity)); } } } } return null; } // Example usage: // public static void main(String[] args) { // BlooioApiClient client = new BlooioApiClient(); // String chatId = "+15551234567"; // String messageId = "msg_abc123def456"; // String apiToken = "YOUR_BEARER_TOKEN"; // // try { // String messageDetails = client.getMessage(chatId, messageId, apiToken); // System.out.println("Message Details: " + messageDetails); // } catch (IOException e) { // e.printStackTrace(); // } // } } ``` -------------------------------- ### Get Message Details (Python) Source: https://docs.blooio.com/messages/getMessage Example using Python to retrieve message details. This script utilizes the `requests` library to perform a GET request to the Blooio API. It requires the chat ID, message ID, and an authorization token. Error handling for non-2xx responses is included. ```python import requests def get_message(chat_id, message_id, token): url = f"https://backend.blooio.com/v2/api/chats/{chat_id}/messages/{message_id}" headers = { "Authorization": f"Bearer {token}" } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching message: {e}") return None # Example usage: # chat_id = '+15551234567' # message_id = 'msg_abc123def456' # api_token = 'YOUR_BEARER_TOKEN' # message_details = get_message(chat_id, message_id, api_token) # if message_details: # print(message_details) ``` -------------------------------- ### Receive Blooio Webhooks Locally with Node.js and Express Source: https://docs.blooio.com/development Set up a local Node.js server using Express to receive and log incoming webhooks from Blooio. The server listens on port 3001 and expects JSON payloads. ```javascript // server.js import express from 'express' const app = express() app.use(express.json()) app.post('/webhooks/blooio', (req, res) => { console.log('Webhook:', req.headers['x-blooio-event'], req.body) res.sendStatus(200) }) app.listen(3001, () => console.log('Listening on http://localhost:3001')) ``` -------------------------------- ### Get Message Details (JavaScript) Source: https://docs.blooio.com/messages/getMessage Example using JavaScript to fetch message details. This code snippet demonstrates how to make a GET request to the Blooio API endpoint for retrieving a specific message. Ensure you replace placeholders with actual chat and message IDs, and include your Bearer token for authentication. ```javascript async function getMessage(chatId, messageId, token) { const url = `https://backend.blooio.com/v2/api/chats/${chatId}/messages/${messageId}`; const headers = { 'Authorization': `Bearer ${token}` }; try { const response = await fetch(url, { method: 'GET', headers: headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log(data); return data; } catch (error) { console.error('Error fetching message:', error); } } // Example usage: // const chatId = '+15551234567'; // const messageId = 'msg_abc123def456'; // const apiToken = 'YOUR_BEARER_TOKEN'; // getMessage(chatId, messageId, apiToken); ``` -------------------------------- ### Account Source: https://docs.blooio.com/api-reference/introduction Validate your key and view devices and usage. ```APIDOC ## GET /v2/api/account ### Description Retrieve account information, including API key validation status, associated devices, and usage statistics. ### Method GET ### Endpoint /v2/api/account ### Response #### Success Response (200) - **api_key_valid** (boolean) - Indicates if the provided API key is valid. - **devices** (array) - A list of devices associated with the account. - **usage** (object) - An object containing usage statistics. - **messages_sent** (integer) - The total number of messages sent. - **messages_received** (integer) - The total number of messages received. #### Response Example ```json { "api_key_valid": true, "devices": ["iPhone 13", "Android Pixel 6"], "usage": { "messages_sent": 1500, "messages_received": 200 } } ``` ``` -------------------------------- ### Get Webhook Details by ID (Java) Source: https://docs.blooio.com/webhooks/getWebhook Retrieves details for a specific webhook using its unique ID in Java. This example uses Apache HttpClient to make a GET request to the Blooio API, including the Authorization header. ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class BlooioClient { public String getWebhook(String webhookId, String token) throws Exception { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet("https://backend.blooio.com/v2/api/webhooks/" + webhookId); request.addHeader("Authorization", "Bearer " + token); try (CloseableHttpResponse response = client.execute(request)) { if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Request failed with status: " + response.getStatusLine().getStatusCode()); } return EntityUtils.toString(response.getEntity()); } } } } ``` -------------------------------- ### Reactions Source: https://docs.blooio.com/api-reference/introduction Add tapback reactions to any message. ```APIDOC ## POST /v2/api/messages/{message_id}/reactions ### Description Add a tapback reaction to a specific message. ### Method POST ### Endpoint /v2/api/messages/{message_id}/reactions ### Parameters #### Path Parameters - **message_id** (string) - Required - The unique identifier of the message to react to. #### Request Body - **reaction** (string) - Required - The reaction to add (e.g., 'like', 'love', 'dislike', 'laugh', 'exclaim', 'question'). ### Response #### Success Response (200) - **message** (string) - Confirmation message of the reaction. #### Response Example ```json { "message": "Reaction added successfully." } ``` ## DELETE /v2/api/messages/{message_id}/reactions ### Description Remove a tapback reaction from a specific message. ### Method DELETE ### Endpoint /v2/api/messages/{message_id}/reactions ### Parameters #### Path Parameters - **message_id** (string) - Required - The unique identifier of the message to remove the reaction from. #### Query Parameters - **reaction** (string) - Required - The reaction to remove. ### Response #### Success Response (200) - **message** (string) - Confirmation message of the reaction removal. #### Response Example ```json { "message": "Reaction removed successfully." } ``` ``` -------------------------------- ### Get Webhook Details by ID (JavaScript) Source: https://docs.blooio.com/webhooks/getWebhook Retrieves details for a specific webhook using its unique ID in JavaScript. This example demonstrates making a GET request to the Blooio API, requiring an Authorization header with a Bearer token. ```javascript async function getWebhook(webhookId) { const response = await fetch(`https://backend.blooio.com/v2/api/webhooks/${webhookId}`, { method: 'GET', headers: { 'Authorization': 'Bearer YOUR_API_TOKEN' } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } ``` -------------------------------- ### Get Message Details (cURL) Source: https://docs.blooio.com/messages/getMessage Example using cURL to retrieve details for a specific message. Requires chat ID and message ID as path parameters. Authentication is handled via a Bearer token in the header. ```curl curl -X GET "https://backend.blooio.com/v2/api/chats/%2B15551234567/messages/msg_abc123def456" ``` -------------------------------- ### Set Blooio API Key as Environment Variable Source: https://docs.blooio.com/development Configure your Blooio API key by exporting it as an environment variable. This is a prerequisite for making authenticated API requests. ```bash export BLOOIO_API_KEY=YOUR_API_KEY ``` -------------------------------- ### Get Authentication Context (Java) Source: https://docs.blooio.com/account/getMe Provides a Java example for retrieving the current authentication context. This can be used in Java-based applications for API integration. ```java import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class BlooioAuth { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://backend.blooio.com/v2/api/me")) .header("Authorization", "Bearer ") .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } } ``` -------------------------------- ### Create Group - Go Source: https://docs.blooio.com/groups/createGroup Example of creating a new group using Go. This code snippet demonstrates how to construct and send a POST request to the `/groups` endpoint, setting the appropriate headers and JSON payload for group creation. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { token := "YOUR_API_TOKEN" url := "https://backend.blooio.com/v2/api/groups" requestBody, err := json.Marshal(map[string]string{ "name": "Sales Team", }) if err != nil { fmt.Println("Error marshaling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+token) client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() var result map[string]interface{} json.NewDecoder(res.Body).Decode(&result) fmt.Println(result) } ``` -------------------------------- ### Track Message Status Source: https://docs.blooio.com/quickstart Poll for status or retrieve full details of a specific message. ```APIDOC ## GET /v2/api/chats/{chatId}/messages/{messageId}/status ### Description Retrieves the status or full details of a specific message. ### Method GET ### Endpoint `https://backend.blooio.com/v2/api/chats/{chatId}/messages/{messageId}/status` ### Parameters #### Path Parameters - **chatId** (string) - Required - The recipient's phone number or email address. - **messageId** (string) - Required - The unique identifier of the message. #### Query Parameters None #### Request Body None ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **message_id** (string) - The unique identifier for the message. - **status** (string) - The current status of the message (e.g., "sent", "delivered", "failed"). - [Other message details] #### Response Example ```json { "message_id": "msg_12345abcde", "status": "delivered", "timestamp": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Get Contact by ID - C# Source: https://docs.blooio.com/contacts/getContact C# code example for fetching contact details using `HttpClient`. It demonstrates setting the Authorization header and processing the JSON response. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Web; public class BlooioApiClient { private readonly HttpClient _httpClient; public BlooioApiClient(string token) { _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); } public async Task GetContactAsync(string contactId) { string encodedContactId = HttpUtility.UrlEncode(contactId); string url = $"https://backend.blooio.com/v2/api/contacts/{encodedContactId}"; HttpResponseMessage response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); // Throws an exception if the response status code is not a success code. return await response.Content.ReadAsStringAsync(); } } ``` -------------------------------- ### Start Local Server with Express.js Source: https://docs.blooio.com/guides/webhooks-local Sets up a basic Express.js server to listen for incoming POST requests on the '/webhooks/blooio' endpoint. It logs the received headers and body to the console and responds with a 200 status code. This server runs on port 3001. ```javascript import express from "express"; const app = express(); app.use(express.json()); app.post("/webhooks/blooio", (req, res) => { console.log("[Blooio]", req.headers["x-blooio-event"], req.body); res.sendStatus(200); }); app.listen(3001, () => console.log("Listening on http://localhost:3001")); ``` -------------------------------- ### List Groups with C# Source: https://docs.blooio.com/groups/listGroups This C# code example shows how to retrieve a list of groups using HttpClient. It demonstrates setting the Authorization header and reading the response content. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class BlooioGroups { public static async Task Main(string[] args) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ""); var response = await client.GetAsync("https://backend.blooio.com/v2/api/groups"); response.EnsureSuccessStatusCode(); // Throw if not 2xx var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` -------------------------------- ### Get Authentication Context (JavaScript) Source: https://docs.blooio.com/account/getMe Provides a JavaScript example for retrieving the current authentication context. This snippet can be integrated into web applications or Node.js services for API interaction. ```javascript fetch('https://backend.blooio.com/v2/api/me', { method: 'GET', headers: { 'Authorization': 'Bearer ' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ```