WhatsApp API for Developers: Documentation and Complete Tutorial [2026]

The WhatsApp API for developers is the gateway for any development team looking to integrate WhatsApp messaging into their applications, support platforms, or automation systems. Through the WhatsApp Business Platform de Meta, developers have access to a complete REST API that allows sending messages, managing templates, receiving notifications via webhook, and building conversational experiences at scale. In this guide, we take you step by step through the architecture, environment configuration, main endpoints, available SDKs by language, and everything you need to get your integration up and running. If you are looking for a general overview of the ecosystem before diving into the code, check our complete WhatsApp Business API guide.
WhatsApp Business API Architecture for Developers
Before writing a single line of code, you need to understand how the WhatsApp API is structured at a technical level. Meta's platform exposes a REST API over HTTPS with token-based authentication, and all incoming communication is managed through webhooks. Understanding this architecture will save you hours of debugging and poor design decisions.
Cloud API vs On-Premise
The WhatsApp Business API is offered in two main modes. The Cloud API is hosted entirely on Meta's infrastructure: you do not need your own servers, you do not manage Docker containers, and updates are automatic. It is the recommended option by Meta since 2022 and the one that offers the fastest access for any WhatsApp API developer.
The On-Premise version requires deploying containers on your own servers or on those of a Business Solution Provider (BSP). It offers greater control over data, but requires a dedicated operations team, certificate management, and manual updates. Meta is progressively deprecating this mode in favor of Cloud API.
For most development teams, the Cloud API is the right choice. If your use case requires strict data residency or extremely high volumes with latencies below 100ms, the On-Premise may make sense, but evaluate it carefully. You can dive deeper into the differences in our WhatsApp Cloud API guide.
Main Endpoints
The API is structured around Meta's Graph API, with the following base pattern:
https://graph.facebook.com/v21.0/{phone-number-id}/{recurso}The most relevant endpoints for a WhatsApp developer are:
- POST /messages: Send text messages, templates, multimedia, locations, contacts, and interactive messages.
- GET /media/{media-id}: Download received multimedia files.
- POST /media: Upload multimedia files for later sending.
- GET /{phone-number-id}: Get information about the associated phone number.
- GET /{waba-id}/message_templates: List approved templates.
- POST /{waba-id}/message_templates: Create new message templates.
Each endpoint returns responses in JSON format and uses standard HTTP error codes. WhatsApp-specific errors include codes such as 131047 (number not registered on WhatsApp) or 131026 (message outside the 24-hour window).
Authentication and Tokens
The authentication system is based on access tokens generated from the Meta for Developers panel. There are two types:
Temporary token: Generated from the Meta Developers console and expires in 24 hours. Useful for quick tests and local development.
Permanent system token: Generated by creating a system user in Business Manager and assigning permissions over the WhatsApp application. This is the token you will use in production.
All requests must include the token in the Authorization header:
curl -X POST \
'https://graph.facebook.com/v21.0/{phone-number-id}/messages' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-H 'Content-Type: application/json' \
-d '{"messaging_product":"whatsapp","to":"34600000000","type":"text","text":{"body":"Hola desde la API"}}'Store the token as an environment variable and never include it directly in the source code. If you want to understand how the entire authentication flow works, we have a detailed explanation in how WhatsApp API works.
Getting Started: Development Environment Setup
Once you understand the architecture, it is time to get your hands on the keyboard. This section covers the complete process from creating the app in Meta to sending your first test message.
Create App on Meta Developers
The starting point is the Meta for Developers portal (developers.facebook.com). Follow these steps:
- Create a Meta Business account: If your company does not have one, you will need to create it at business.facebook.com. It is a mandatory requirement to access the WhatsApp Business API.
- Create a new application: In the Meta Developers panel, select "Create application" and choose the "Business" type. Associate it with your Meta Business account.
- Add WhatsApp as a product: On the application page, search for "WhatsApp" in the products section and click "Set up". This will automatically generate a test number (sandbox) and a WhatsApp Business Account ID (WABA ID).
- Obtain credentials: In the WhatsApp configuration section, you will find the Phone Number ID, the WABA ID, and a token temporal. Note all three values; you will need them for API calls.
- Add test numbers: In the sandbox environment, you can only send messages to previously verified numbers. Add your personal number as a test recipient.
With these five steps you have the minimum environment to start making API calls. If you need to configure a complete WhatsApp Business API developer account for production, the process includes verifying your company and requesting a dedicated phone number.
Set Up Webhook
Webhooks are the mechanism through which Meta notifies you of incoming events: received messages, delivery statuses, template changes, and more. To configure them:
- Create a public endpoint: You need a server accessible from the internet that accepts POST requests. During development, you can use tools like ngrok to expose a local server.
- Verification endpoint (GET): Meta sends a GET request with the parameters
hub.mode,hub.verify_tokenandhub.challenge. Your server must verify that theverify_tokenmatches the one you have configured and return the value ofhub.challenge.
// Ejemplo en Node.js (Express)
app.get('/webhook', (req, res) => {
const VERIFY_TOKEN = process.env.WEBHOOK_VERIFY_TOKEN;
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
res.status(200).send(challenge);
} else {
res.sendStatus(403);
}
});- Reception endpoint (POST): Incoming message notifications arrive as POST with a JSON payload. Your server must respond with a
200 OKas quickly as possible and process the message asynchronously.
app.post('/webhook', (req, res) => {
const body = req.body;
if (body.object === 'whatsapp_business_account') {
body.entry?.forEach(entry => {
entry.changes?.forEach(change => {
if (change.field === 'messages') {
const message = change.value.messages?.[0];
if (message) {
console.log('Mensaje recibido:', message.text?.body);
// Procesar mensaje de forma asincrona
}
}
});
});
res.sendStatus(200);
} else {
res.sendStatus(404);
}
});- Register the URL in Meta Developers: In the WhatsApp configuration panel, enter the URL of your endpoint and the verification token. Subscribe to the
messagesfield to receive incoming message notifications.
The configuration of WhatsApp Business API webhooks is critical for any bidirectional integration. Without webhooks, you can only send messages but not receive responses. If you want to explore open-source alternatives for webhook management, check our guide on Evolution API for WhatsApp.
Testing with Postman
Before writing code in your preferred language, verify that everything works with Postman:
- Create a new POST request: URL
https://graph.facebook.com/v21.0/{phone-number-id}/messages. - Configure authentication: In the Authorization tab, select "Bearer Token" and enter your temporary token.
- Define the body: Select "raw" and "JSON", and paste the following payload:
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "34600000000",
"type": "text",
"text": {
"preview_url": false,
"body": "Hola, este es un mensaje de prueba desde la API"
}
}- Send and verify: If the response includes a
messagesfield with anid, the send was successful. Verify that the message reaches the recipient number.
This test flow with Postman is the same regardless of the programming language you will use later. It is the most direct way to isolate authentication or configuration issues before complicating things with application logic.
Endpoint Guide: Sending Messages, Templates, and Multimedia
The WhatsApp API offers multiple message types. Each one has its own payload format and restrictions. This section documents the most used by WhatsApp API developers with ready-to-use code examples.
POST /messages
The central API endpoint. All message types are sent through the same URL, differentiated by the type field in the payload. The base format always includes:
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "{numero_destino}",
"type": "{tipo_mensaje}",
...
}The available message types are: text, template, image, video, audio, document, sticker, location, contacts, interactive and reaction. Each type adds specific fields to the payload.
For simple text messages:
curl -X POST \
'https://graph.facebook.com/v21.0/{phone-number-id}/messages' \
-H 'Authorization: Bearer {TOKEN}' \
-H 'Content-Type: application/json' \
-d '{
"messaging_product": "whatsapp",
"to": "34600000000",
"type": "text",
"text": {"body": "Hola, este es un mensaje de texto"}
}'A critical aspect: text messages can only be sent within the 24-hour conversation window. If the user has not interacted with you in the last 24 hours, you must use an approved template. If you want to dive deeper into the template system, check our article on WhatsApp API message templates.
Templates API
The message templates (message templates) are the only message type you can send outside the 24-hour window. They must be approved by Meta before use.
To send a template:
curl -X POST \
'https://graph.facebook.com/v21.0/{phone-number-id}/messages' \
-H 'Authorization: Bearer {TOKEN}' \
-H 'Content-Type: application/json' \
-d '{
"messaging_product": "whatsapp",
"to": "34600000000",
"type": "template",
"template": {
"name": "bienvenida_cliente",
"language": {"code": "es"},
"components": [
{
"type": "body",
"parameters": [
{"type": "text", "text": "Maria"}
]
}
]
}
}'To create templates programmatically:
curl -X POST \
'https://graph.facebook.com/v21.0/{waba-id}/message_templates' \
-H 'Authorization: Bearer {TOKEN}' \
-H 'Content-Type: application/json' \
-d '{
"name": "confirmacion_pedido",
"language": "es",
"category": "UTILITY",
"components": [
{
"type": "BODY",
"text": "Hola {{1}}, tu pedido {{2}} ha sido confirmado."
}
]
}'The approval process usually takes between a few minutes and 24 hours. The available categories are UTILITY, MARKETING and AUTHENTICATION, and each has different pricing.
Media API
Multimedia sending allows sharing images, videos, documents, and audio. You can reference files by public URL or upload them first to Meta's servers:
Send by URL:
{
"messaging_product": "whatsapp",
"to": "34600000000",
"type": "image",
"image": {
"link": "https://ejemplo.com/producto.jpg",
"caption": "Nuestro nuevo producto"
}
}Pre-upload to Meta:
curl -X POST \
'https://graph.facebook.com/v21.0/{phone-number-id}/media' \
-H 'Authorization: Bearer {TOKEN}' \
-F 'file=@/ruta/local/documento.pdf' \
-F 'type=application/pdf' \
-F 'messaging_product=whatsapp'The response includes a media_id that you can use in the id field of the multimedia message instead of link. Uploaded files are automatically deleted after 30 days.
Interactive Messages
The interactive messages are one of the most powerful features for WhatsApp API developers. They allow creating interfaces with buttons, selection lists, and quick replies directly in the chat.
Quick reply buttons (maximum 3):
{
"messaging_product": "whatsapp",
"to": "34600000000",
"type": "interactive",
"interactive": {
"type": "button",
"body": {"text": "¿Como podemos ayudaros?"},
"action": {
"buttons": [
{"type": "reply", "reply": {"id": "soporte", "title": "Soporte tecnico"}},
{"type": "reply", "reply": {"id": "ventas", "title": "Ventas"}},
{"type": "reply", "reply": {"id": "info", "title": "Informacion"}}
]
}
}
}Selection lists (up to 10 options per section):
{
"messaging_product": "whatsapp",
"to": "34600000000",
"type": "interactive",
"interactive": {
"type": "list",
"body": {"text": "Seleccionad una opcion:"},
"action": {
"button": "Ver opciones",
"sections": [
{
"title": "Productos",
"rows": [
{"id": "plan_basico", "title": "Plan Basico", "description": "49 EUR/mes"},
{"id": "plan_pro", "title": "Plan Pro", "description": "99 EUR/mes"}
]
}
]
}
}
}Interactive messages are essential for building conversational flows without natural language processing. For more advanced integrations with chatbots on WhatsApp Business, combine them with state logic in your backend.
SDKs and Libraries for WhatsApp API by Language
Meta does not offer official SDKs dedicated exclusively to WhatsApp (except the WhatsApp Business SDK for Node.js in beta). However, the community ecosystem has generated robust libraries for the main languages. Below we present the most relevant options for each language.
Python
Python is one of the most popular languages among WhatsApp API developers, especially for bots and automations.
Recommended libraries:
- heyoo: Lightweight and simple wrapper for the Cloud API. Ideal for quick prototypes.
- whatsapp-python-sdk (from Meta): Experimental client available in Meta's official repository.
- requests + custom code: For many teams, a custom module with
requestsis sufficient.
Example with requests:
import requests
import os
PHONE_NUMBER_ID = os.environ['WA_PHONE_NUMBER_ID']
ACCESS_TOKEN = os.environ['WA_ACCESS_TOKEN']
def enviar_mensaje(destinatario: str, texto: str) -> dict:
url = f'https://graph.facebook.com/v21.0/{PHONE_NUMBER_ID}/messages'
headers = {
'Authorization': f'Bearer {ACCESS_TOKEN}',
'Content-Type': 'application/json'
}
payload = {
'messaging_product': 'whatsapp',
'to': destinatario,
'type': 'text',
'text': {'body': texto}
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.json()
# Uso
resultado = enviar_mensaje('34600000000', 'Hola desde Python')
print(f"Mensaje enviado: {resultado['messages'][0]['id']}")To send WhatsApp messages with Python at scale, consider using aiohttp for async calls or a task queue like Celery to handle high volumes.
Node.js
Node.js is the natural choice for real-time integrations thanks to its asynchronous model. It is the language with the best official support from Meta.
Recommended libraries:
- whatsapp-business-api-sdk (Meta): Official SDK in beta. Supports Cloud API and offers TypeScript typing.
- whatsapp-web.js: Unofficial library based on the web version (not recommended for production).
- axios/node-fetch + custom code: The most flexible option.
Example with axios:
const axios = require('axios');
const PHONE_NUMBER_ID = process.env.WA_PHONE_NUMBER_ID;
const ACCESS_TOKEN = process.env.WA_ACCESS_TOKEN;
async function enviarMensaje(destinatario, texto) {
const url = `https://graph.facebook.com/v21.0/${PHONE_NUMBER_ID}/messages`;
const { data } = await axios.post(url, {
messaging_product: 'whatsapp',
to: destinatario,
type: 'text',
text: { body: texto }
}, {
headers: {
'Authorization': `Bearer ${ACCESS_TOKEN}`,
'Content-Type': 'application/json'
}
});
return data;
}
// Uso
enviarMensaje('34600000000', 'Hola desde Node.js')
.then(res => console.log('Mensaje enviado:', res.messages[0].id))
.catch(err => console.error('Error:', err.response?.data));To configure the reception webhook for WhatsApp Business API in Node.js, use Express as shown in the previous section. If you are looking for a more complete solution that handles queues, retries, and scaling, you can automate WhatsApp Business with specialized frameworks.
PHP
PHP remains the dominant language in many web development teams, especially in projects with Laravel or WordPress. Integration with the WhatsApp API is straightforward via cURL or Guzzle.
Recommended libraries:
- netflie/whatsapp-cloud-api: Complete Composer package with support for all message types.
- guzzlehttp/guzzle + custom code: For teams that prefer full control.
Example with native cURL:
For a more detailed guide on PHP integration, including examples with Laravel and webhook management, check our dedicated article on WhatsApp API with PHP.
Java
Java is common in enterprise environments and robust backend systems. WhatsApp API integration is typically done with HttpClient (Java 11+) or libraries like OkHttp.
Example with HttpClient:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class WhatsAppApi {
private static final String PHONE_NUMBER_ID = System.getenv("WA_PHONE_NUMBER_ID");
private static final String ACCESS_TOKEN = System.getenv("WA_ACCESS_TOKEN");
public static String enviarMensaje(String destinatario, String texto)
throws Exception {
String url = String.format(
"https://graph.facebook.com/v21.0/%s/messages", PHONE_NUMBER_ID
);
String payload = String.format("""
{
"messaging_product": "whatsapp",
"to": "%s",
"type": "text",
"text": {"body": "%s"}
}
""", destinatario, texto);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + ACCESS_TOKEN)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString()
);
return response.body();
}
}For WhatsApp Business API integration with Java in Spring Boot projects, you can create a @Service that encapsulates these calls and adds error handling, retries with exponential backoff, and structured logging. The combination with a multi-agent system allows managing multiple WhatsApp numbers from a single application; check our guide on WhatsApp multi-agent for more details.
Frequently Asked Questions
Is the WhatsApp API free for developers?
The WhatsApp Cloud API is free in terms of access: there is no cost for the API itself. However, Meta charges for each initiated conversation. Prices vary depending on the type of conversation (utility, marketing, authentication, or service) and the recipient's country. The first 1,000 service conversations per month are free. For Spain, marketing conversations cost approximately 0.0615 EUR and utility conversations 0.0200 EUR.
How do you develop with the WhatsApp API?
To start developing with the WhatsApp API, you need to create an application on the Meta for Developers portal, obtain an access token, configure a webhook to receive messages, and make your first calls to the POST /messages endpoint. The entire initial setup process, from account creation to sending the first message, can be completed in less than 30 minutes following the steps described in this guide.
How can I send 5,000 WhatsApp messages at once?
For bulk sends through the WhatsApp Business API, you need to use message templates approved by Meta. Sending is done through individual calls to the POST /messages endpoint for each recipient. There is no native bulk send endpoint. To manage 5,000 sends, implement a task queue (such as Celery, Bull, or RabbitMQ) that processes sends in parallel while respecting the API rate limits (80 messages per second on Cloud API). Also, verify that your number has the required sending tier (Tier 3 allows up to 100,000 messages daily).
Who are the developers of WhatsApp?
WhatsApp was created by Jan Koum and Brian Acton in 2009. Both had previously worked at Yahoo. Meta (then Facebook) acquired WhatsApp in 2014 for 19 billion dollars. Currently, the platform development is handled by Meta's engineering teams, and the WhatsApp Business Platform (including the API) is managed by Meta's enterprise products division.
How to get the WhatsApp Business API key?
The WhatsApp API does not use a traditional API key, but rather an OAuth access token. To obtain it, go to the Meta for Developers portal, open your WhatsApp application, and generate it from the configuration section. For production, create a system user in Business Manager and generate it as a permanent token with the whatsapp_business_messaging and whatsapp_business_management.
What is the price of the WhatsApp API?
The WhatsApp API has a conversation-based pricing model. There is no license cost or API access fee. Costs depend on the type of conversation and the recipient's market. For the Spanish market: marketing conversations at 0.0615 EUR, utility at 0.0200 EUR, authentication at 0.0340 EUR, and service conversations free (the first 1,000 per month). BSPs may add additional margins on top of these base prices.
How GuruSup Enhances Your WhatsApp API for Developers
Integrating the WhatsApp Business API is only the first part of the puzzle. The real challenge for development teams is building a support experience on top of that integration that scales without multiplying the human team. That is where GuruSup.
Key GuruSup Features
GuruSup is an autonomous support platform that connects directly to the WhatsApp Business API and adds an artificial intelligence layer on top of communication. Instead of managing webhooks, message queues, and routing logic on your own, GuruSup offers you:
- Trained AI Agents with your company's documentation and knowledge base, capable of automatically resolving frequent queries through WhatsApp.
- Native WhatsApp Cloud API integration: no need to configure servers, webhooks, or manage tokens manually.
- Multi-agent panel that allows your support team to manage conversations that the AI agent escalates to a human, all from a unified interface.
- Conversation analytics to identify patterns, improve automatic responses, and measure customer satisfaction.
For development teams, GuruSup drastically reduces integration time: instead of building message processing logic from scratch, you can connect your WhatsApp Business account and have a functional support system in minutes.
How to Get Started with GuruSup
Getting started is straightforward: sign up at gurusup.com, connect your WhatsApp Business account, and configure your first AI agent with your knowledge base. GuruSup handles all the API complexity, webhooks, and routing for you, so your team can focus on what really matters: improving the product and your customers' experience.
Try GuruSup for free: automate your customer support with AI agents on WhatsApp.


