### Python: Bottle Web Server Setup for 46elks Example Source: https://46elks.se/docs/webrtc-client-connect Sets up a minimal web server using the Bottle framework to serve static files and handle API routes. It defines routes for the root ('/') to serve 'webrtc.html' and '/jssip-3.10.0.js' for the JavaScript library, and '/make-call' for initiating calls. ```python from bottle import run, get, post, static_file, request @get('/') def index(): return static_file('webrtc.html', root='.') @get('/jssip-3.10.0.js') def jssip(): return static_file('jssip-3.10.0.js', root='.') # ... make_call function definition ... run(host='localhost', port=8080) ``` -------------------------------- ### Example JSON Response for Get Subaccount by ID Source: https://46elks.se/docs/get-subaccount-id This is an example of the JSON response structure returned when successfully retrieving a subaccount's details. It includes fields like 'secret', 'created', 'usagelimit', 'id', 'name', and 'balanceused'. Not all fields are always present, depending on the subaccount's status and usage. ```JSON { "secret": "D81DEF1B65E19A83DBCEA0BE0D89D082", "created": "2014-12-08T13:18:07.625000", "usagelimit": 910000, "id": "af3d05a159669e1951c5301bc6a61bac", "name": "This Co", "balanceused": 12300 } ``` -------------------------------- ### Bottle.py Webserver Example Source: https://46elks.se/docs/webrtc-client-connect A Python snippet using Bottle.py to handle incoming requests and interact with the 46elks API for making calls. ```APIDOC ## Bottle.py Webserver Example ### Description This Python code snippet demonstrates a basic web server using the Bottle.py framework to handle API requests, specifically for initiating phone calls via the 46elks API. ### Method GET, POST (as defined by Bottle routes) ### Endpoint `/` (example root endpoint), `/make-call` (example endpoint for initiating calls) ### Parameters #### Path Parameters None (in the provided snippet) #### Query Parameters None (in the provided snippet) #### Request Body (for `/make-call` endpoint) - **phoneNumber** (string) - Required - The destination phone number. - **webrtcNumber** (string) - Required - The originating WebRTC number. ### Request Example (Conceptual) ```python import urllib.request import urllib.parse from base64 import b64encode elks_username = "YOUR_API_USERNAME" elks_password = "YOUR_API_PASSWORD" # Example of constructing a request to 46elks API to make a call url = "https://api.46elks.com/a1/calls" data = { "from": webrtcNumber, # The originating number "to": phonenumber, # The destination number "call_id": "some_unique_call_id" } encoded_data = urllib.parse.urlencode(data).encode('utf-8') base64_auth = b64encode(f"{elks_username}:{elks_password}".encode()).decode() headers = { "Authorization": f"Basic {base64_auth}", "Content-Type": "application/x-www-form-urlencoded" } req = urllib.request.Request(url, data=encoded_data, headers=headers, method='POST') try: with urllib.request.urlopen(req) as response: print(response.read().decode()) except Exception as e: print(f"Error making call: {e}") ``` ### Response #### Success Response (200) Indicates the web server successfully processed the request and potentially made the API call. #### Response Example ```json { "status": "success", "message": "Call initiated" } ``` ``` -------------------------------- ### Example JSON Response with Dryrun Enabled Source: https://46elks.se/docs/index This JSON object shows an example response when the 'dryrun' parameter is enabled. Instead of sending an SMS, the API returns a simulated response including the estimated cost and the number of parts the message would be split into. This is useful for verifying message formatting and cost without actual sending. ```json { "status": "created", "direction": "outgoing", "from": "Elks", "estimated_cost": 10000, "to": "+46700000000", "parts": 2, "message": "This is an example of a response with the dryrun parameter enabled. 🫎" } ``` -------------------------------- ### Get MMS by ID - Example Response Structure Source: https://46elks.se/docs/show-mms-id This is an example JSON response when successfully retrieving an MMS by its ID. It includes details such as the message ID, direction, sender, recipient, creation timestamp, message content, and a list of image IDs. ```json { "id": "m84af96809ff8989f3668c93aaaedb69c", "direction": "incoming", "from": "+46700000000", "created": "2016-08-18T09:55:31.116000", "to": "+46700000000", "message": "Message text.", "images": [ "m84af96809ff8989f3668c93aaaedb69c-i0" ] } ``` -------------------------------- ### 46elks Call Event Payload Example Source: https://46elks.se/docs/call-actions An example of the payload received via POST request when a call event occurs. This payload contains details about the call, including direction, participants, timestamps, actions taken, state, cost, duration, and a unique ID. ```text direction=outgoing&from=%2B46766862965&start=2020-05-25T10%3A09%3A03.246556&created=2020-05-25T10%3A08%3A54.367600&actions=%5B%7B%22play%22%3A+%22https%3A%2F%2Ffiles.46elks.com%2Fben%2Fcustomer-service.mp3%22%2C+%22result%22%3A+%22failed%22%2C+%22why%22%3A+%22hangup%22%7D%5D&to=%2B46766866966&state=success&cost=5700&duration=5&id=c52eb46be23533b89110d703e5976d38a ``` -------------------------------- ### Send MMS using Java Source: https://46elks.se/docs/send-mms This Java example utilizes the Unirest library to send an MMS message. It sets up a POST request to the 46elks API, providing sender, recipient, and image URL through form fields and basic authentication. ```java import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; public class UnirestSendMMS { public static void main(String[] args) { try { System.out.println("Sending MMS"); HttpResponse response = Unirest.post("https://api.46elks.com/a1/MMS") .basicAuth("", "") .field("to", "+46700000000") .field("from", "+46700000000") .field("image", "https://yourserver.example/images/treasuremap.jpg") .asString(); System.out.println(response.getBody()); } catch (Exception e){ System.out.println(e); } } } ``` -------------------------------- ### Incoming Call Request Payload Example Source: https://46elks.se/docs/handle-client-call An example of the HTTP POST request payload sent by 46elks when a client initiates a voice call. It includes call direction, unique ID, originating number, destination number, and creation timestamp. ```http POST https://yourapp.example/elks/calls direction=incoming&id=sf8425555e5d8db61dda7a7b3f1b91bdb&from=%2B4600100100&to=%2B46766861004&created=2018-08-13T13%3A57%3A23.741000 ``` -------------------------------- ### Send SMS using GET Source: https://46elks.se/docs/get-instead-of-post Demonstrates how to send an SMS using a GET request by appending '/POST' to the SMS endpoint. All parameters must be URL-encoded query parameters. ```APIDOC ## GET /a1/sms/POST ### Description Sends an SMS message using a GET request. This is an alternative to the POST method when POST is not feasible. ### Method GET ### Endpoint `https://api.46elks.com/a1/sms/POST` ### Parameters #### Query Parameters - **to** (string) - Required - The recipient's phone number. - **from** (string) - Required - The sender's phone number or name. - **message** (string) - Required - The content of the SMS message. ### Request Example ``` GET https://api.46elks.com/a1/sms/POST?to=+46701234567&from=ElkCo&message=Hello! ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the SMS sending operation. - **message_id** (string) - A unique identifier for the sent message. #### Response Example ```json { "status": "sent", "message_id": "m_12345abcde" } ``` ``` -------------------------------- ### Send MMS using Node.js Source: https://46elks.se/docs/send-mms This Node.js example uses the `axios` library to send an MMS. It defines an asynchronous function `sendMMS` that takes credentials, constructs a POST request with sender, recipient, and image URL, and includes basic authentication in the headers. ```javascript const axios = require("axios"); const sendMMS = async credentials => { try { const res = await axios.post( "https://api.46elks.com/a1/mms", new URLSearchParams({ from: "noreply", to: "+46700000002", message: "Bring a sweater, it’s cold outside!", image: "https://46elks.com/press/46elks-blue-png" }), { headers: { "Authorization": "Basic " + credentials } }); console.log(res.data); } catch (err) { console.log(err); } } const username = "USERNAME"; const password = "PASSWORD"; const authKey = Buffer.from(username + ":" + password).toString("base64"); sendMMS(authKey); ``` -------------------------------- ### Example Incoming Call Payload Source: https://46elks.se/docs/receive-call This is an example of the data sent in the HTTP POST request to your webhook when a call is received. It includes call identification and participant numbers. ```http direction=incoming& callid=c45072a1eeafebccc3dffbd4d27b5ebcc& from=%2B46706861004& to=%2B46706860000 ``` -------------------------------- ### Update Subaccount API Response Example Source: https://46elks.se/docs/update-subaccount This is an example JSON response when successfully updating a subaccount via the 46elks API. It includes details such as the subaccount's secret, creation timestamp, usage limit, ID, name, and current credit usage. ```JSON { "secret": "D81DEF1B65E19A83DBCEA0BE0D89D082", "created": "2014-12-08T13:18:07.625000", "usagelimit": 99999999999, "id": "af3d05a159669e1951c5301bc6a61bac", "name": "This Co", "balanceused": 12300 } ``` -------------------------------- ### Example JSON Response for Call History Source: https://46elks.se/docs/call-history An example JSON structure representing the response when fetching call history. It details call direction, participants, timestamps, cost, duration, and unique identifiers. ```JSON { "data": [ { "direction": "outgoing", "from": "+46700000000", "to": "+4670371815", "created": "2018-02-20T11:55:27.756000", "owner": "ufb9e21cb046b15feeed314e732a0e9d1", "actions": [ { "connect": "+46704508449", "result": "success" } ], "start": "2018-02-20T11:55:41.528000", "state": "success", "cost": 11400, "timeout": 60, "duration": 30, "legs": [ { "duration": 17, "to": "+46704508449", "state": "success", "from": "+46700000000" } ], "id": "c70b23624c022a93a87907712cf804aca" } // ... ], "next": "2018-02-20T10:48:03.349000" } ``` -------------------------------- ### Get Recording WAV file Source: https://46elks.se/docs/get-recording-id-wav Retrieves a specific call recording in WAV format. Recordings are available for 72 hours after creation. ```APIDOC ## GET /a1/recordings/{ID}.wav ### Description Retrieves a specific call recording in WAV format. Recordings are available for 72 hours after creation. ### Method GET ### Endpoint /a1/recordings/{ID}.wav ### Parameters #### Path Parameters - **ID** (string) - Required - The unique identifier of the recording to retrieve. ### Response #### Success Response (200) - The response will be a .wav file containing the audio recording. ``` -------------------------------- ### Incoming Call Response Structure Example Source: https://46elks.se/docs/handle-client-call The required JSON response structure for the webhook to continue an incoming voice call. It specifies the number to connect to, the caller ID, and actions for call failures like busy or network issues, referencing audio files for playback. ```json { "connect": "+4634090510", "callerid": "+46700000000", "failed": {"play": "https://yourapp.example/callfailed.wav"} "busy": {"play": "https://yourapp.example/callbusy.wav"} } ``` -------------------------------- ### 46elks API Call Playback Result Source: https://46elks.se/docs/voice-play This example shows the expected result format when using the 'Play' action with the 46elks API. It details the parameters 'callid' and 'result', indicating the success or failure of the playback operation. ```http POST https://yourapp.example/elks/calls Parameter | Description ---|--- callid | The unique id of the call in our systems. result | Either ”ok” or ”failed”, depending on if playback was successful. ``` -------------------------------- ### Allocate Number with Java Source: https://46elks.se/docs/allocate-number This Java example uses the Unirest library to allocate a virtual phone number. It constructs a POST request to the 46elks API, including authentication and parameters for country and capabilities. The response is then printed to the console. ```Java import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; public class UnirestSendcalls { public static void main(String[] args) { try { System.out.println("Sending calls"); HttpResponse response = Unirest.post("https://api.46elks.com/a1/numbers") .basicAuth("","") .field("capabilities", "sms,voice") .field("country", "se") .asString(); System.out.println(response.getBody()); } catch (Exception e){ System.out.println(e); } } } ``` -------------------------------- ### Send SMS using various programming languages Source: https://46elks.se/docs/send-sms This snippet demonstrates how to send an SMS message using the 46elks API. It requires API credentials and specifies the sender, recipient, and message content. The examples cover cURL, Elixir, Java, Node.js, PHP, Python, and Ruby. ```curl curl https://api.46elks.com/a1/sms \ -u : \ -d from=CurlyElk \ -d to=+46700000000 \ -d message="Bring a sweater, it's cold outside" ``` ```elixir import HTTPotion.base authdata = [basic_auth: {'', ''}] request = %{ "from" => "ElixirElk", "to" => "+46700000000", "message" => "Bring a sweater, it’s cold outside!" } request_data = URI.encode_query(request) HTTPotion.start HTTPotion.post("https://api.46elks.com/a1/sms", [body: request_data , ibrowse: authdata] ) ``` ```java import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; public class UnirestSendSMS { public static void main(String[] args) { try { System.out.println("Sending SMS"); HttpResponse response = Unirest.post("https://api.46elks.com/a1/sms") .basicAuth("","") .field("to", "+46700000000") .field("from", "JavaElk") .field("message", "Bring a sweater, it’s cold outside!") .asString(); System.out.println(response.getBody()); } catch (Exception e){ System.out.println(e); } } } ``` ```javascript // API credentials const username = "< API Username >"; const password = "< API Password >"; const auth = Buffer.from(username + ":" + password).toString("base64"); let data = { from: "NodeElk", to: "+46700000001", message: "Bring a sweater, it’s cold outside!" } data = new URLSearchParams(data); data = data.toString(); fetch("https://api.46elks.com/a1/sms", { method: "post", body: data, headers: {"Authorization": "Basic " + auth} }) .then(res => res.json()) .then(json => console.log(json)) .catch(err => console.log(err)) ``` ```php function sendSMS ($sms) { $username = "USERNAME"; $password = "PASSWORD"; $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => 'Authorization: Basic '. base64_encode($username.':'.$password). "\r\n". "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query($sms,'','&'), 'timeout' => 10 ))); $response = file_get_contents("https://api.46elks.com/a1/sms", false, $context); if (!strstr($http_response_header[0],"200 OK")) return $http_response_header[0]; return $response; } $sms = array( "from" => "PHPElk", /* Can be up to 11 alphanumeric characters */ "to" => "+46700000000", /* The mobile number you want to send to */ "message" => "Bring a sweater, it's cold outside!", );echo sendSMS($sms); ``` ```python import requests response = requests.post( 'https://api.46elks.com/a1/sms', auth = (API_USERNAME, API_PASSWORD), data = { 'from': 'PythonElk', 'to': '+46700000000', 'message': "It's cold outside, bring a sweater!" } ) print(response.text) ``` ```ruby require 'net/http' uri = URI('https://api.46elks.com/a1/sms') req = Net::HTTP::Post.new(uri) req.basic_auth '', '' req.set_form_data( :from => 'RubyElk', :to => '+46704508449', :message => 'Login code 123456' ) res = Net::HTTP.start( uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| http.request req end puts res.body ``` -------------------------------- ### Allocate Number with Python Source: https://46elks.se/docs/allocate-number This Python example uses the requests library to allocate a virtual phone number. It constructs a POST request to the 46elks API, including authentication and parameters for country and capabilities. The response text is then printed. ```Python import requests auth = ( '', '' ) fields = { 'country': 'se', 'capabilities': 'sms,voice' } response = requests.post( "https://api.46elks.com/a1/numbers", data=fields, auth=auth ) print(response.text) ``` -------------------------------- ### Make a Call (WebRTC Sample) Source: https://46elks.se/docs/webrtc-client-connect Sample JavaScript code demonstrating how to initiate an outgoing call using JsSIP and the 46elks API. ```APIDOC ## Make a Call (WebRTC Sample) ### Description This sample demonstrates how to make an outgoing phone call directly from a WebRTC client using JsSIP and a backend server that interacts with the 46elks API. ### Method POST (for the backend fetch request) ### Endpoint `/make-call` (for the backend endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for `/make-call` endpoint) - **phoneNumber** (string) - Required - The destination phone number to call. - **webrtcNumber** (string) - Required - The originating WebRTC number. ### Request Example (Frontend JavaScript) ```javascript // Assuming phonenumber and webrtcNumber are defined let formData = new FormData(); formData.append("phoneNumber", phonenumber); formData.append("webrtcNumber", webrtcNumber); fetch("/make-call", {method: "post", body: formData}); ``` ### Response #### Success Response (200) Indicates the call initiation request was successfully sent to the backend. #### Response Example N/A (Backend response not detailed in sample) ``` -------------------------------- ### Fetch MMS History (GET Request) Source: https://46elks.se/docs/mms-history This snippet demonstrates how to fetch MMS history using a GET request to the 46elks API. It includes the base URL and optional parameters like 'start', 'end', and 'limit' for filtering and pagination. The response is a JSON object containing a list of MMS messages and a link to the next page if available. At most 100 MMS can be retrieved per request. ```HTTP GET https://api.46elks.com/a1/mms # Optional request parameters: # start: 2018-02-14T09:52:07.302000 (Retrieve MMS before this date) # end: 2018-02-14T09:52:07.302000 (Retrieve MMS after this date) # limit: 40 (Limit the number of results on each page) ``` -------------------------------- ### WebRTC SIP Client Configuration and Call Initiation (HTML/JavaScript) Source: https://46elks.se/docs/webrtc-client-connect This snippet demonstrates how to configure and use a WebRTC SIP client with JsSIP to make and receive phone calls. It includes client setup, event handling for call states, and interaction with a backend server to initiate calls. Requires the JsSIP library. ```html ``` -------------------------------- ### Get Recording History (API Request) Source: https://46elks.se/docs/get-recordings Fetches a list of recordings made via the 46elks API. The request can be filtered by start and end dates, and the number of results can be limited. Recordings are available for 72 hours after creation. ```HTTP GET https://api.46elks.com/a1/recordings ``` -------------------------------- ### Static Control Flow in JSON Source: https://46elks.se/docs/call-actions Demonstrates how to implement basic call control flow directly within the JSON structure using keywords like 'failed', 'success', and 'next'. This is an alternative to using webhooks but is not recommended for complex scenarios. ```APIDOC ## Static Control Flow in JSON ### Description This section illustrates how to manage call control flow directly within the JSON payload for simple scenarios. Keywords like `failed`, `success`, and `next` can be used to define behavior based on action outcomes. The `connect` action also supports `busy` for handling busy signals. ### Method N/A (This is a JSON structure for API requests) ### Endpoint N/A (This is a JSON structure for API requests) ### Request Body Example ```json { "connect": "+46701740605", "timeout": "15", "busy": { "connect": "+46701740664", "timeout": "15", "busy": { "connect": "+46701740622", "timeout": "15" } } } ``` ### Parameters #### Request Body - **connect** (string) - Required - The phone number to connect to. - **timeout** (string) - Optional - The timeout duration in seconds before proceeding to the next step. - **busy** (object) - Optional - Defines actions to take if the line is busy. Can be nested. - **failed** (object/string) - Optional - Triggers when the current action fails. - **success** (object/string) - Optional - Triggers when the current action succeeds. - **next** (object/string) - Optional - Triggers regardless of the action's success or failure. ### Response #### Success Response (200) Responses will vary based on the actions defined in the JSON structure. #### Response Example (Response examples depend on the specific control flow implemented) ``` -------------------------------- ### Prerequisites Source: https://46elks.se/docs/overview Requirements for using the 46elks API, including account details and basic knowledge. ```APIDOC ## Prerequisites ### Description In order to use the 46elks API you need the following: ### Requirements * A 46elks account with an active payment method * A computer with internet access * Basic knowledge of how to copy/paste and run example code ### Webhook Integration Requirements If you plan to use API features that require webhook integration you will also need some kind of publicly reachable backend service. This can be anything: a VPS running Rails / Django / Express etc., an AWS Lambda function, a few lines of code on Google App Scripts or a bash script running on some old computer in your closet. ``` -------------------------------- ### Get SMS by ID using GET Request Source: https://46elks.se/docs/show-sms-id This snippet demonstrates how to retrieve a specific SMS message by its ID using a GET request to the 46elks API. The 'id' parameter is required to identify the SMS. The response includes details such as sender, recipient, message content, and status. ```HTTP GET https://api.46elks.com/a1/sms/{id} ``` -------------------------------- ### Get MMS Image File using HTTP GET Source: https://46elks.se/docs/get-image-id-jpg This snippet demonstrates how to fetch an MMS image file by its ID and specified format using an HTTP GET request. Ensure you replace '{ID}' and '{FILE_FORMAT}' with actual values. The API will return the raw image file data. ```http GET https://api.46elks.com/a1/images/{ID}.{FILE_FORMAT} ``` -------------------------------- ### Get MMS by ID - HTTP Request Source: https://46elks.se/docs/show-mms-id This snippet shows the HTTP GET request to retrieve a specific MMS message by its ID. Replace '{id}' with the actual MMS ID. The response will be in JSON format. ```http GET https://api.46elks.com/a1/mms/{id} ``` -------------------------------- ### Initiate Phone Call via 46elks API (Python/Bottle) Source: https://46elks.se/docs/webrtc-client-connect This Python snippet demonstrates a backend webserver using the Bottle framework to handle requests for initiating phone calls. It uses the 46elks API credentials to make an outgoing call request, requiring API username and password. It also handles basic HTTP errors. ```python import json import urllib.parse import urllib.request from base64 import b64encode from urllib.error import HTTPError, URLError from bottle import get, post, request, run, static_file # Your 46elks API credentials. elks_username = "API username" elks_password = "API password" # A number bought through the 46elks dashboard or the one ``` -------------------------------- ### Get MMS by ID Source: https://46elks.se/docs/show-mms-id Retrieves details of a specific MMS message using its unique identifier. ```APIDOC ## GET /a1/mms/{id} ### Description Retrieves details of a specific MMS message using its unique identifier. ### Method GET ### Endpoint /a1/mms/{id} ### Parameters #### Path Parameters - **id** (string) - Required - ID of the MMS. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The unique identifier of the MMS. - **direction** (string) - Indicates if the MMS was 'incoming' or 'outgoing'. - **from** (string) - The sender's phone number. - **created** (string) - The timestamp (UTC) when the MMS was created. - **to** (string) - The recipient's phone number in E.164 format. - **message** (string) - The text content of the MMS. Not included if `dontlog=message` is set. - **images** (list) - An array containing the IDs of the images attached to the MMS. - **status** (string) - The status of the MMS (e.g., 'recieved', 'sent', 'delivered'). - **cost** (integer) - The cost of the MMS in 10000s of the account's currency (SEK or EUR). #### Response Example ```json { "id": "m84af96809ff8989f3668c93aaaedb69c", "direction": "incoming", "from": "+46700000000", "created": "2016-08-18T09:55:31.116000", "to": "+46700000000", "message": "Message text.", "images": [ "m84af96809ff8989f3668c93aaaedb69c-i0" ], "status": "delivered", "cost": 3500 } ``` ``` -------------------------------- ### Get SMS by ID Source: https://46elks.se/docs/show-sms-id Retrieves details of a specific SMS message using its unique ID. ```APIDOC ## GET /a1/sms/{id} ### Description Retrieves details of a specific SMS message using its unique ID. ### Method GET ### Endpoint https://api.46elks.com/a1/sms/{id} ### Parameters #### Path Parameters - **id** (string) - Required - ID of the SMS. #### Query Parameters - **direction** (string) - Optional - Incoming or outgoing. - **from** (string) - Optional - The sender. - **to** (string) - Optional - The phone number of the recipient, in E.164 format. - **created** (string) - Optional - The time in UTC when the SMS was created. - **delivered** (string) - Optional - The time in UTC when the SMS was delivered. - **message** (string) - Optional - The content of the SMS, same as the message parameter. Not included in the response if dontlog=message is set. - **status** (string) - Optional - created (recieved by our servers), sent (sent from us to the carrier), delivered (confirmed delivered to the recipient) or failed (could not be delivered). - **cost** (integer) - Optional - The cost of sending the SMS. Specified in 10000s of the currency of the account (SEK or EUR). For example, for an account with currency SEK, a cost of 3500 means that it cost 0.35SEK. Learn more about the details of pricing. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the SMS. - **direction** (string) - Indicates if the SMS is 'incoming' or 'outgoing'. - **from** (string) - The sender's identifier. - **created** (string) - The timestamp when the SMS was created (UTC). - **to** (string) - The recipient's phone number in E.164 format. - **message** (string) - The content of the SMS. #### Response Example ```json { "id": "s3633fa8e62f823e52fbc67ebf6925ab5", "direction": "incoming", "from": "SMSElk", "created": "2016-08-18T09:55:31.116000", "to": "+46700000000", "message": "I'm not a moose." } ``` ``` -------------------------------- ### Python: Basic Authentication Header for 46elks API Source: https://46elks.se/docs/webrtc-client-connect Generates a Base64 encoded authentication token required for interacting with the 46elks API. It takes username and password, encodes them, and formats them into the 'Authorization: Basic ' header. ```python from base64 import b64encode elks_username = "your_username" elks_password = "your_password" auth_bytes = f"{elks_username}:{elks_password}".encode() auth_token = b64encode(auth_bytes).decode() headers = { "Authorization": f"Basic {auth_token}" } ``` -------------------------------- ### API Overview Source: https://46elks.se/docs/overview General information about the 46elks API, including base URL, authentication, and content type. ```APIDOC ## API Overview ### Description The 46elks API is a simple HTTP API that you can use to interact with all our products. All endpoints follow the following basic design choices: ### Base URL `https://api.46elks.com/a1/` ### Authentication Basic Auth ### Request Content Type `application/x-www-form-urlencoded` ### Webhooks Used for asynchronous events (HTTP callbacks). ``` -------------------------------- ### Send SMS using GET Request - HTTP Source: https://46elks.se/docs/get-instead-of-post This snippet demonstrates how to send an SMS using a GET request to the 46elks API. All parameters must be URL-encoded and appended as query parameters. This method is an alternative to POST requests for security or technical reasons. ```http GET https://api.46elks.com/a1/sms/POST?to=+46701234567&from=ElkCo&message=Hello! ``` -------------------------------- ### Get Subaccount by ID (API Request) Source: https://46elks.se/docs/get-subaccount-id This snippet demonstrates how to make a GET request to retrieve details of a specific subaccount using its ID. The request requires the subaccount's ID in the URL path. The response is a JSON object containing various details about the subaccount. ```HTTP GET https://api.46elks.com/a1/subaccounts/{id} ``` -------------------------------- ### WebRTC Client Configuration Source: https://46elks.se/docs/webrtc-client-connect Configure your WebRTC SIP client with the necessary settings for connecting to the 46elks service. ```APIDOC ## WebRTC Client Configuration ### Description Configure your WebRTC SIP client with the following settings. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters #### Client Settings - **Servers** (string) - Required - The WebSocket server URL for the WebRTC client. - **Username** (string) - Required - Your 46elks client number (without the '+' sign). - **Password** (string) - Required - The password for your SIP number, found in the number object in the API. - **URI** (string) - Required - The combination of server and number in the format `[number]@[server_address]`. #### Outgoing Phone Calls Special configuration is required to enable outgoing phone calls directly from a SIP or webRTC client. Contact 46elks support for assistance. ### Request Example N/A (Configuration) ### Response N/A (Configuration) ``` -------------------------------- ### Get Account Information (API Request) Source: https://46elks.se/docs/get-account This snippet demonstrates how to make a GET request to the 46elks API to retrieve account information. It shows the endpoint URL and the expected response structure, which includes details like the account's mobile number, display name, ID, currency, balance, and email. ```HTTP GET https://api.46elks.com/a1/me ``` ```JSON { "mobilenumber": "+46700000000", "displayname": "Your name or company", "id": "u5a9566c072160b318445d163949bf505", "currency": "SEK", "balance": 9670500, "email": "help@46elks.com" } ``` -------------------------------- ### Python: Initiate a WebRTC Call with 46elks Source: https://46elks.se/docs/webrtc-client-connect Initiates an outgoing call using the 46elks API. It constructs the necessary data payload including the 'from' number, 'to' number, and 'voice_start' instructions for connecting the call. Error handling for HTTP and URL errors is included. ```python import urllib.request import urllib.parse import json from bottle import request, post from http.client import HTTPError from urllib.error import URLError # Assuming elks_number, headers are defined elsewhere @post('/make-call') def make_call(): phone_number = request.forms.phoneNumber webrtc_number = request.forms.webrtcNumber voice_start = {'connect': phone_number, 'callerid': elks_number} data = urllib.parse.urlencode([ ('from', elks_number), ('to', webrtc_number), ('voice_start', json.dumps(voice_start)) ]) req = urllib.request.Request( 'https://api.46elks.com/a1/calls', data=data.encode(), headers=headers, method='POST' ) try: response = urllib.request.urlopen(req) except HTTPError as e: print(e.code, e.reason) print(e.read().decode()) except URLError as e: print("Could not reach server.") print(e.reason) else: print(response.read().decode()) ``` -------------------------------- ### Get Virtual Phone Number Information (REST API) Source: https://46elks.se/docs/show-number-id Retrieves details about a specific virtual phone number using its ID. This is a GET request to the 46elks API. ```REST GET https://api.46elks.com/a1/numbers/{id} ``` -------------------------------- ### Get Account Information Source: https://46elks.se/docs/get-account Retrieves the details of the authenticated account, including ID, currency, display name, mobile number, email, and balance. ```APIDOC ## GET /a1/me ### Description Retrieves the details of the authenticated account. ### Method GET ### Endpoint https://api.46elks.com/a1/me ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (string) - Unique account id. - **currency** (string) - The currency used by the account, for example SEK or EUR. - **displayname** (string) - The name of the account. - **mobilenumber** (string) - The cell phone number of the account owner in E.164 format. - **email** (string) - The email of the account owner. - **balance** (integer) - Current balance of the account. #### Response Example ```json { "mobilenumber": "+46700000000", "displayname": "Your name or company", "id": "u5a9566c072160b318445d163949bf505", "currency": "SEK", "balance": 9670500, "email": "help@46elks.com" } ``` ``` -------------------------------- ### POST /make-call Source: https://46elks.se/docs/webrtc-client-connect Initiates an outbound call from a WebRTC client to a specified phone number using the 46elks API. ```APIDOC ## POST /make-call ### Description Initiates an outbound call from a WebRTC client to a specified phone number using the 46elks API. The API connects the call and sets the caller ID to the provided 46elks number. ### Method POST ### Endpoint /make-call ### Parameters #### Query Parameters - **phoneNumber** (string) - Required - The phone number to call. - **webrtcNumber** (string) - Required - The identifier for the WebRTC client to initiate the call from. ### Request Body This endpoint uses form data for request parameters. ### Request Example ``` phoneNumber=+1234567890&webrtcNumber=webrtc_client_id ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that the call initiation request was processed. #### Response Example ```json { "message": "Call initiated successfully" } ``` #### Error Response - **code** (integer) - The HTTP error code. - **reason** (string) - A description of the error. #### Error Response Example ```json { "code": 400, "reason": "Bad Request" } ``` ``` -------------------------------- ### Get MMS Image File Source: https://46elks.se/docs/get-image-id-jpg Retrieves the image file associated with a specific MMS image ID. Supports various file formats. ```APIDOC ## GET /a1/images/{ID}.{FILE_FORMAT} ### Description Returns the image file of the image with the specified ID. ### Method GET ### Endpoint `https://api.46elks.com/a1/images/{ID}.{FILE_FORMAT}` ### Parameters #### Path Parameters - **ID** (string) - Required - The unique identifier of the MMS image. - **FILE_FORMAT** (string) - Required - The desired file format for the image (e.g., jpg, png). ### Response #### Success Response (200) - The API will return the image file in the specified format. ``` -------------------------------- ### Configure Call Recording with Recordcall Option Source: https://46elks.se/docs/voice-recordcall This snippet demonstrates how to use the 'recordcall' option when initiating a voice action. It specifies the recording URL and an optional 'next' URL for subsequent actions. The recording is automatically made available via webhook after the call. ```json { "connect": "+46700000000", "recordcall": "https://myserver.se/newrecording", "next": "https://myserver.se/nextaction" } ``` -------------------------------- ### Get Subaccount by ID Source: https://46elks.se/docs/get-subaccount-id Retrieves details of a specific subaccount using its ID. This endpoint is useful for fetching information about a subaccount, including its name, creation date, usage limits, and current balance. ```APIDOC ## GET /a1/subaccounts/{id} ### Description Retrieves details of a specific subaccount using its ID. ### Method GET ### Endpoint https://api.46elks.com/a1/subaccounts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - ID of the subaccount, used as API username for requests by the subaccount. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **secret** (string) - The secret of the account, used as API password for requests by the subaccount. Only present on active subaccounts. - **created** (string) - Time and date when the account was created. - **usagelimit** (integer) - The max amount of credits the subaccount may use. - **id** (string) - The ID of the subaccount. - **name** (string) - Name of the account. - **balanceused** (integer) - The amount of credits the subaccount has used. Only present if credits has been used. - **deactivated** (string) - Time and date when the subaccount was deactivated. Only present on deactivated subaccounts. - **active** (string) - Set to "no" on deactivated subaccounts. Only present on deactivated subaccounts. #### Response Example ```json { "secret": "D81DEF1B65E19A83DBCEA0BE0D89D082", "created": "2014-12-08T13:18:07.625000", "usagelimit": 910000, "id": "af3d05a159669e1951c5301bc6a61bac", "name": "This Co", "balanceused": 12300 } ``` ```