WhatsApp's Business Management API gives you access to metrics and analytics about your WhatsApp Business Account (WABA). You can get two types of data about your account:
When querying the API endpoint, you’re required to specify whether you want analytics for either messages or conversations by adding analytics
or conversation_analytics
as a parameter for the URL.
For example, this is a sample request if you want to get message analytics about your account:
https://graph.facebook.com/v14.0/{whatsapp-business-account-ID} ?fields=analytics .{filtering-parameters} &{access-token}
In this sample, we specified that we want to retrieve message analytics for phone numbers linked to the WABA that has a unique WABA ID. You will learn more about getting your WABA ID and access token in the Requirements section that follows.
Additionally, when making a request, you can apply filtering parameters to refine the result. The Business Management API endpoint supports six filtering parameters in total. You must have the following:
start
: If you specify a start date, the response does not include the messages sent before the given date.
end
: If you specify an end date, the response does not include the messages sent after the given date.
granularity
: How granular do you want the retrieved analytics to be? Possible values include HALF_HOUR, DAY, and MONTH.
As for conversation_analytics
, you have nine filtering parameters, of which three — start
, end
, and granularity
— are required.
For this tutorial, you will need to:
Install Python and pip on your local dev machine.*
Sign up for a developer account on Meta for Developers, create a Business Type App, and add a WhatsApp Business Account to the App.
Set up—on the Add Products to Your App page, click the Set Up button on the WhatsApp option.
After creating a WhatsApp Business Type App, you will get a WABA ID and a temporary access token. You need these two keys for the rest of this tutorial, so hold on to them.
You can add your personal WhatsApp number as the sender or use the test phone number provided by WhatsApp.
Set up a Python development environment and install the required packages.
Create a folder, give it a name and then navigate to the folder using a command-line tool. For this blog, we’ll use the requests library for making HTTP requests and the popular Matplotlib library for creating static, animated, and interactive visualizations. Run the following command to install them:
pip install requests matplotlib
Now, you’ll be able to use Python requests to query the API for analytics data from WhatsApp, then use Matplotlib to visualize the metrics by plotting a graph with the data points received from the API.
Start by requesting the analytics data. To do that, create a file named sent.py
in your application folder and import the dependencies required for this task:
import datetime import requests import matplotlib.pyplot as plt
Next, create the API GET
request to get the analytics using your WABA ID and access token. You can find these values on the dashboard of your developer account on Meta for Developer. The code for the GET
request is as follows:
key = 'put-your-access-token-here' waba_id = 'put-your-waba-id-here' res = requests.get(f'https://graph.facebook.com/v14.0/{waba_id}?fields=analytics.start(1662174000).end(1662548446).granularity(DAY)&access_token={key}') dict = res.json() print(dict)
In the request above, we represented the start date in UNIX-style, as the API requires. You can use this free converter to convert between human-readable and UNIX timestamps. The code converts the response to JSON format on the last line and prints it.
Execute the following command to run the code:
python app.py
If the phone numbers linked to the WABA are used to send messages in the specified timeframe, we get a response dictionary object which looks like the following one:
{ "analytics": { "phone_numbers": [ "16505550111", "16505550112", "16505550113" ], "country_codes": [ "US", ], "granularity": "DAY", "data_points": [ { "start": 1662174000, "end": 1662260400, "sent": 199251, "delivered": 183001 }, { "start": 1662260400, "end": 1662346800, "sent": 162489, "delivered": 141234 }, { "start": 1662346800, "end": 1662433200, "sent": 67902, "delivered": 53902 }, { "start": 1662433200, "end": 1662519600, "sent": 129521, "delivered": 117832 } ] }, "id": "952305634918047" }
In this case, the data_points
list contains four dictionaries. Each contains the number of messages that the linked WhatsApp numbers sent and delivered during the specified date range.
Now that you have the data, you must retrieve the necessary information. Since we want to visualize the number of messages sent each day, we must get start
and sent
values from each dictionary.
To do that, loop through the data points using the Python for...in
loop. Convert the start time from UNIX style to a human-readable version for each data object. Then, get only the numerical day of the month and add it to the list of days. Store the number of sent messages in another list named no_of_msgs_sent
:
days = [] no_of_msgs_sent = [] data_points = dict.get("analytics").get("data_points") for point in data_points: # Get date in human readable format x = datetime.datetime.fromtimestamp(point.get('start')) # Get just the day in string format y = x.strftime("%d") days.append(y) # Add the number of sent messages to the list no_of_msgs_sent.append(point.get('sent')) print(days) print(no_of_msgs_sent) If you run the code, you get two lists: ['03', '04', '05', '06'] // days [196093, 147649, 61988, 132465] // number of messages Now that you have what you need, it's time to visualize it. Add the following code to app.py: plt.plot(days, no_of_msgs_sent) plt.title('Our Graph') plt.xlabel('Days') plt.ylabel('Number of messages sent') plt.show()
Here, you’re plotting a basic graph with the days along the x-axis and the number of sent messages along the y-axis.
Save the file and run your code. If you’re on Linux and you get an error that says the following:
UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
Make sure you have tkinter installed. If you don’t, run the following command to install it:
sudo apt-get install python3-tk
If you run the code, you’ll get a graph that looks like this:
Next, you’ll create a graph to visualize the number of delivered messages.
In the previous section, we didn't include phone numbers in the request. As a result, the API returned information for all phone numbers linked to the WABA within the specified start and end dates.
However, if you want to retrieve analytical data for one or multiple phone numbers but not all of them, you need to put the phone numbers in an array and pass it to the .phone_numbers
method when creating the request:
res = requests.get(f'https://graph.facebook.com/v14.0/{waba_id}?fields=analytics.start(1662174000).end(1662548446).phone_numbers([16505550111, // others]).granularity(DAY)&access_token={key}')
The remaining code in sent.py
remains the same. You only get the analytics for the specified phone numbers when you execute it.
In the last two sections, we plotted a graph to visualize the number of messages sent each day by the linked phone numbers through WhatsApp. Now, let’s plot a graph to visualize the number of messages delivered daily.
Create a new file and name it delivered.py
. Next, copy the code from sent.py
into delivered.py
.
Next, make a few changes to the code in delivered.py
. First, rename the variable at the top from no_of_msgs_sent
to no_of_msgs_del
to reflect the kind of data you’re storing.
Next, in the for...in
loop, change the value in the point.get
method from sent
to delivered
. Here’s a snippet of how your code should look like after you make the changes:
# Variables go here for point in data_points: # Code for getting human readable date goes here # Now add the number of delivered messages to the list no_of_msgs_del.append(point.get('delivered')) print(day) print(no_of_msgs_del) Finally, specify no_of_msgs_del in the plt.plot method and update the label shown on the y-axis: plt.plot(days, no_of_msgs_del) plt.title('Our Graph') plt.xlabel('Days') plt.ylabel('Number of messages delivered') plt.show()
Once you run the code on your terminal (with python delivered.py
), you’ll get a graph like the one below.
Now that you’ve represented two sets of analytics data for messages, you will next represent the cost of messages using conversation_analytics
.
Once again, create a new file for this section, and name the file cost.py
. Copy the code from sent
.py
into cost
.py
. Now let’s make a few modifications.
First, modify the request code. Since you’re getting the conversation information, set the fields
parameter to conversation_analytics
and set granularity
to daily
.
res = requests.get(f'https://graph.facebook.com/v14.0/{waba_id}?fields=conversation_analytics.start(1662174000).end(1662548446).granularity(DAILY).phone_numbers([])&access_token={key}')
Note that the conversation_anaytics
field supports several other filtering parameters for getting other kinds of information. To learn more, read the full documentation.
After making the above request, you should get a response object very similar to the following:
{ "conversation_analytics": { 'data': { "data_points": [ { "start": 1662174000, "end": 1662260400, "conversation": 5250, "cost": 45.0532 }, { "start": 1662260400, "end": 1662346800, "conversation": 2250, "cost": 25.0290 }, { "start": 1662346800, "end": 1662433200, "conversation": 800, "cost": 0.0000 }, { "start": 1662433200, "end": 1662519600, "conversation": 3150, "cost": 33.2015 } ] } }, }
As seen above, the data_points
are inside the data dictionary. Each data point in the dictionary has a conversation amount and cost.
Next, in cost.py
, change the variable at the top from no_of_msgs_del
to cost_of_convo
. In the for...in
loop, change the value in the point.get
method from delivered
to cost
. Here’s a snippet of how your code should look like after you make the changes:
days = [] cost_of_convo = [] data_points = dict.get('conversation_analytics').get("data").get("data_points") for point in data_points: x = datetime.datetime.fromtimestamp(point.get('start')) y = x.strftime("%d") days.append(y) # Add the cost of messages in each data point cost_of_convo.append(point.get('cost')) Now, to plot a graph visualizing it: plt.plot(days, cost_of_convo) plt.title('Our Graph') plt.xlabel('Days') plt.ylabel('Cost of messages sent') plt.show()
If you run your code using the terminal (with python cost.py
), you’ll get a graph like this:
And that's it!
To take things further, you can follow the same method to visualize other metrics that the WhatsApp Business Management API provides.
In this tutorial, we used the matplotlib data visualization library to visualize data showing the number of messages sent per day, the number of messages delivered per day, and the cost of each message conversation.
The WhatsApp Business Management API gives you these filtering parameters and many more, which you can use to specify the metrics you want in each request. To learn more, check out the full API documentation.
As a developer, the WhatsApp Business Management API gives you relevant information and metrics from the WhatsApp account of your users. For example, you can show your users the number of WhatsApp messages they have sent on a given day on their dashboard.
The possibilities are endless!
*Meta cannot be held responsible for any third party apps.Sign up for monthly updates from Meta for Developers.