WhatsApp API in Rust: reqwest, Typed Errors and an axum Webhook

Send WhatsApp messages from Rust with Meta’s Cloud API: reqwest for text and templates, typed errors and retries, and an axum webhook that checks the signature.

Illustration: a Rust file in an editor next to a phone receiving a WhatsApp order update (sample data)

To send a WhatsApp message from Rust, POST JSON to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with reqwest, a Bearer access token and serde_json. Meta’s Cloud API is plain HTTPS and JSON, so you don’t need a WhatsApp crate: reqwest, serde and tokio cover sending, and axum plus hmac cover the webhook.

This guide builds one small program, src/main.rs: a send client, text and template messages, typed errors with a retry for rate limits, and an axum webhook that answers Meta’s handshake and checks the X-Hub-Signature-256 signature. It uses Graph API v27.0, the latest in Meta’s changelog (4 November 2026). For other languages, see the Go, Python and Node.js guides.

Key takeaways

  • Meta doesn’t publish a Rust SDK. reqwest with the json feature is all you need to send.
  • Every message is the same POST with a different type; build the body with serde_json::json!.
  • Turn Meta’s error object into a typed Rust error, and retry only on throughput errors such as 130429.
  • In the webhook, hash the raw body bytes with your app secret and compare with verify_slice, which runs in constant time.
  • Crates that drive WhatsApp Web aren’t the official API and can put a business number at risk.

Is there an official WhatsApp crate for Rust?

No. Meta’s Cloud API pages describe HTTP requests and name no Rust package. Your own small client with reqwest and serde, as in this guide, always matches Meta’s current format. Community crates that wrap the same Graph API can work too, if they call graph.facebook.com and keep up with new API versions. Crates that log in as a linked device, like WhatsApp Web, are a different thing: they aren’t Meta’s Business API.

WhatsApp says unofficial apps break its Terms of Service and can get an account banned, so a WhatsApp Web crate is the wrong tool for a number your business depends on. The full comparison is in official vs unofficial WhatsApp APIs.

Before you start: accounts and Cargo.toml

  • A phone number ID (not the phone number itself) and a permanent system-user token. The token in API Setup expires quickly; the Cloud API setup guide shows how to make a lasting one, and this guide shows where to find the phone number ID.
  • Your app secret and a verify token you make up, for the webhook.
  • A test recipient who has agreed to hear from you, such as your own phone on Meta’s test number.
  • Stable Rust and a new project: cargo new wa.

Add these lines under [dependencies] in Cargo.toml. They were the current versions on docs.rs when this was written. reqwest’s .json() needs the json feature, which isn’t on by default:

CrateCargo.toml line
reqwestreqwest = { version = "0.13", features = ["json"] }
serdeserde = { version = "1", features = ["derive"] }
serde_jsonserde_json = "1"
tokiotokio = { version = "1", features = ["full"] }
axumaxum = "0.8"
hmac, sha2, hexhmac = "0.13", sha2 = "0.11", hex = "0.4"

The code reads WHATSAPP_TOKEN, PHONE_NUMBER_ID, APP_SECRET and VERIFY_TOKEN from the environment.

A send client with reqwest

Start src/main.rs with these lines. Each row is one line or one item; every import is used by the end of the file.

Linesrc/main.rs
1use std::{collections::HashMap, env, sync::Arc, time::Duration};
2use axum::{body::Bytes, extract::{Query, State}, http::{HeaderMap, StatusCode}, routing::get, Router};
3use hmac::{Hmac, KeyInit, Mac}; use serde::Deserialize; use serde_json::{json, Value}; use sha2::Sha256;
4const API_VERSION: &str = "v27.0";
5#[derive(Debug, Deserialize)] struct MetaError { code: i64, message: String }
6#[derive(Debug, Deserialize)] struct ErrorBody { error: MetaError }
7#[derive(Debug)] enum SendError { Http(reqwest::Error), Meta { status: u16, code: i64, message: String }, Unexpected(String) }
8impl From<reqwest::Error> for SendError { fn from(e: reqwest::Error) -> Self { SendError::Http(e) } }
9struct WhatsApp { http: reqwest::Client, token: String, url: String }
10impl WhatsApp { fn from_env() -> Self { let phone_id = env::var("PHONE_NUMBER_ID").expect("PHONE_NUMBER_ID not set");
11Self { http: reqwest::Client::builder().timeout(Duration::from_secs(15)).build().expect("HTTP client"),
12token: env::var("WHATSAPP_TOKEN").expect("WHATSAPP_TOKEN not set"), url: format!("https://graph.facebook.com/{API_VERSION}/{phone_id}/messages") } }
13async fn send(&self, payload: &Value) -> Result<String, SendError> {
14let res = self.http.post(&self.url).bearer_auth(&self.token).json(payload).send().await?;
15let status = res.status().as_u16(); let body: Value = res.json().await?;
16if let Ok(e) = serde_json::from_value::<ErrorBody>(body.clone()) { return Err(SendError::Meta { status, code: e.error.code, message: e.error.message }); }
17body["messages"][0]["id"].as_str().map(str::to_owned).ok_or_else(|| SendError::Unexpected(body.to_string())) } }

Run cargo fmt after pasting. Notes:

  • One reqwest::Client for the whole program, as reqwest’s docs recommend, so connections are reused.
  • bearer_auth adds the Authorization: Bearer header, and .json() sets Content-Type: application/json, the two headers in Meta’s examples.
  • The error check reads the body, not only the status, because Meta puts the useful part in error.code and error.error_data.details. Meta says to build error handling on the code, since the titles in message will eventually be deprecated.

Send a text and a template message

A free-form text reaches the customer only inside the 24-hour customer service window, which opens when they message or call you. Outside it, you can send only an approved template. Add this function under the impl block:

Linesrc/main.rs
18async fn send_examples(wa: &WhatsApp) -> Result<(), SendError> {
19let text = json!({"messaging_product": "whatsapp", "recipient_type": "individual", "to": "919800000000", "type": "text", "text": {"preview_url": false, "body": "Hi Priya, your table for 4 is booked for 8 pm tonight."}});
20println!("text sent: {}", wa.send(&text).await?);
21let params = json!([{"type": "text", "text": "Priya"}, {"type": "text", "text": "ORD-1042"}]);
22let template = json!({"messaging_product": "whatsapp", "recipient_type": "individual", "to": "919800000000", "type": "template", "template": {"name": "order_update", "language": {"code": "en"}, "components": [{"type": "body", "parameters": params}]}});
23println!("template sent: {}", send_with_retry(wa, &template).await?); Ok(()) }
  • to is the number with its country code, as digits, of someone who opted in.
  • The returned ID (wamid…) is what delivery and read statuses refer to later, so store it with your order or ticket.
  • A success means Meta accepted the request, not that the phone received it. Delivery arrives later at your webhook.
  • The template must be APPROVED, and its name and language code must match WhatsApp Manager exactly. Positional values follow {{1}}, {{2}} in order; for a template made with named variables, add "parameter_name": "first_name" to each value, and order no longer matters.

Headers with images, and buttons, are extra components; the JSON for each is in how to send a WhatsApp template message with the API, and it drops into the same json! call. Why free text fails after a day is explained in the WhatsApp 24-hour rule.

Errors, rate limits and retries

Because send returns SendError::Meta with Meta’s code, you can match on it. These come up most:

CodeMeaningWhat your Rust code should do
190Access token expiredStop and alert; retrying won’t help. Use a permanent system-user token
131047More than 24 hours since the customer last repliedSend an approved template instead
132001Template doesn’t exist in that language or isn’t approvedFix the name or language code; don’t retry
130429Cloud API throughput reachedWait and retry, with a growing delay
131056Too many messages to the same person in a short timeReturned to the caller: Meta allows about 1 message every 6 seconds to the same person, so reschedule it; others can still be sent
4 or 80007App or WhatsApp Business Account API rate limitSlow down the whole job and retry later

Meta’s throughput page gives each business phone number 80 messages per second by default, raised automatically to 1,000 when the number is eligible. Here is a retry that waits only on the throughput code, 130429:

Linesrc/main.rs
24async fn send_with_retry(wa: &WhatsApp, payload: &Value) -> Result<String, SendError> {
25let mut delay = Duration::from_secs(1);
26for attempt in 1..=4 { match wa.send(payload).await {
27Err(SendError::Meta { code: 130429, .. }) if attempt < 4 => { tokio::time::sleep(delay).await; delay *= 2; }
28other => return other, } }
29unreachable!("the fourth attempt always returns") }

For a list of customers, send in a loop with this function rather than spawning hundreds of tasks at once. More on limits in WhatsApp API rate limits, and every code in WhatsApp API error codes.

Receive messages with an axum webhook

Meta sends incoming messages and delivery statuses to a URL you own: a GET handshake when you save the URL, then signed POSTs. One axum route handles both:

Linesrc/main.rs
30type HmacSha256 = Hmac<Sha256>;
31struct AppState { verify_token: String, app_secret: String }
32async fn verify(State(s): State<Arc<AppState>>, Query(q): Query<HashMap<String, String>>) -> Result<String, StatusCode> {
33let ok = !s.verify_token.is_empty() && q.get("hub.mode").map(String::as_str) == Some("subscribe") && q.get("hub.verify_token") == Some(&s.verify_token);
34if ok { Ok(q.get("hub.challenge").cloned().unwrap_or_default()) } else { Err(StatusCode::FORBIDDEN) } }
35fn valid_signature(secret: &str, body: &[u8], header: Option<&str>) -> bool {
36let Some(hex_sig) = header.and_then(|h| h.strip_prefix("sha256=")) else { return false };
37let Ok(sig) = hex::decode(hex_sig) else { return false };
38let Ok(mut mac) = HmacSha256::new_from_slice(secret.as_bytes()) else { return false };
39mac.update(body); mac.verify_slice(&sig).is_ok() }
40async fn receive(State(s): State<Arc<AppState>>, headers: HeaderMap, body: Bytes) -> StatusCode {
41let sig = headers.get("x-hub-signature-256").and_then(|v| v.to_str().ok());
42if s.app_secret.is_empty() || !valid_signature(&s.app_secret, &body, sig) { return StatusCode::UNAUTHORIZED; }
43tokio::spawn(handle(body)); StatusCode::OK }
44async fn handle(body: Bytes) { let Ok(update) = serde_json::from_slice::<Value>(&body) else { return };
45for entry in update["entry"].as_array().into_iter().flatten() { for change in entry["changes"].as_array().into_iter().flatten() { let value = &change["value"];
46for m in value["messages"].as_array().into_iter().flatten() { println!("message {} from {}: {}", m["id"], m["from"], m["text"]["body"]); }
47for st in value["statuses"].as_array().into_iter().flatten() { println!("status {}: {}", st["id"], st["status"]); } } } }
  1. Handshake (lines 32 to 34): Meta sends hub.mode=subscribe, your verify token and a random hub.challenge. Return the challenge with a 200; Meta sends nothing until this passes.
  2. Signature (lines 35 to 39): the header is sha256= plus the hex HMAC-SHA256 of the raw body, keyed with your app secret. verify_slice compares the tags in constant time (the digest crate uses ct_eq), so don’t compare strings with == yourself.
  3. Raw bytes first (line 40): Bytes must be the last extractor, because it reads the body. Check the signature on those exact bytes, then parse.
  4. Answer, then work (line 43): the 200 goes out before processing. In production, use a queue or a database table instead of a bare tokio::spawn.

Wire it up in main, test, then go live

Linesrc/main.rs
48#[tokio::main] async fn main() {
49if env::args().nth(1).as_deref() == Some("send") { if let Err(e) = send_examples(&WhatsApp::from_env()).await { eprintln!("send failed: {e:?}"); } return; }
50let state = Arc::new(AppState { verify_token: env::var("VERIFY_TOKEN").unwrap_or_default(), app_secret: env::var("APP_SECRET").unwrap_or_default() });
51let app = Router::new().route("/webhook", get(verify).post(receive)).with_state(state);
52let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap(); axum::serve(listener, app).await.unwrap(); }
  1. Send: cargo run -- send with the four variables set sends the text and the template to your test number and prints both message IDs.
  2. Handshake: start the server with cargo run, then curl "localhost:8080/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=12345" should print 12345. A wrong token gives 403.
  3. Signed POST: set BODY='{"entry":[]}' and SIG=$(printf %s "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}'), then curl -i -X POST -H "X-Hub-Signature-256: sha256=$SIG" -d "$BODY" localhost:8080/webhook should return 200. Change one body character: 401.
  4. Go live: run cargo build --release, deploy behind a public HTTPS address with a valid certificate (Meta doesn’t accept self-signed ones), save https://your-domain/webhook and your verify token as the callback URL in your Meta app, and subscribe to the messages field.

Payload shapes and status types are explained in WhatsApp Cloud API webhooks. If the handshake passes but nothing arrives, work through WhatsApp webhook not receiving messages.

Rust with Automate AI, or no code at all

Automate AI can run the WhatsApp side instead: it connects your number to Meta, receives the webhooks, and gives you a shared inbox, campaigns and no-code chatbots.

For developers, Automate AI also has its own REST API with API keys, endpoints for contacts, messages, templates, campaigns and automations, developer webhooks with logs, and a Postman collection. There’s no Rust SDK, but the same reqwest pattern works against the REST API. The API and webhooks come with the AI + Automation Plan and Series 4; see the WhatsApp Business API page and pricing.

Frequently asked questions

How do I send a WhatsApp message from Rust?

Build the body with serde_json::json! (messaging_product: "whatsapp", to, type and the message object) and POST it with reqwest to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with bearer_auth(token). The reply holds the message ID.

Is there an official WhatsApp crate for Rust?

No. Meta publishes the Cloud API as HTTP requests and names no Rust package, so reqwest and serde are enough.

Why does my Rust webhook fail the signature check?

Usually because the body was parsed before hashing, or a different secret was used. Take the body as Bytes, hash those exact bytes with your app secret, strip sha256= from the header, hex-decode it and call verify_slice.

Can I send to someone who hasn’t messaged me?

Only with an approved template, and only if they have opted in. Free-form text needs an open 24-hour window.

Which Graph API version should I use?

The latest in Meta’s changelog. On 2 December 2026 that is v27.0, released on 4 November 2026. Keep it in one constant.

Sources

  1. Meta: Send messages
  2. Meta: Templates overview
  3. Meta: Create a webhook endpoint
  4. Meta: Throughput
  5. Meta: Error codes
  6. Meta: Graph API changelog
  7. docs.rs: reqwest
  8. docs.rs: hmac

WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.