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.

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
jsonfeature is all you need to send. - Every message is the same POST with a different
type; build the body withserde_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:
| Crate | Cargo.toml line |
|---|---|
| reqwest | reqwest = { version = "0.13", features = ["json"] } |
| serde | serde = { version = "1", features = ["derive"] } |
| serde_json | serde_json = "1" |
| tokio | tokio = { version = "1", features = ["full"] } |
| axum | axum = "0.8" |
| hmac, sha2, hex | hmac = "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.
| Line | src/main.rs |
|---|---|
| 1 | use std::{collections::HashMap, env, sync::Arc, time::Duration}; |
| 2 | use axum::{body::Bytes, extract::{Query, State}, http::{HeaderMap, StatusCode}, routing::get, Router}; |
| 3 | use hmac::{Hmac, KeyInit, Mac}; use serde::Deserialize; use serde_json::{json, Value}; use sha2::Sha256; |
| 4 | const 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) } |
| 8 | impl From<reqwest::Error> for SendError { fn from(e: reqwest::Error) -> Self { SendError::Http(e) } } |
| 9 | struct WhatsApp { http: reqwest::Client, token: String, url: String } |
| 10 | impl WhatsApp { fn from_env() -> Self { let phone_id = env::var("PHONE_NUMBER_ID").expect("PHONE_NUMBER_ID not set"); |
| 11 | Self { http: reqwest::Client::builder().timeout(Duration::from_secs(15)).build().expect("HTTP client"), |
| 12 | token: env::var("WHATSAPP_TOKEN").expect("WHATSAPP_TOKEN not set"), url: format!("https://graph.facebook.com/{API_VERSION}/{phone_id}/messages") } } |
| 13 | async fn send(&self, payload: &Value) -> Result<String, SendError> { |
| 14 | let res = self.http.post(&self.url).bearer_auth(&self.token).json(payload).send().await?; |
| 15 | let status = res.status().as_u16(); let body: Value = res.json().await?; |
| 16 | if let Ok(e) = serde_json::from_value::<ErrorBody>(body.clone()) { return Err(SendError::Meta { status, code: e.error.code, message: e.error.message }); } |
| 17 | body["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::Clientfor the whole program, as reqwest’s docs recommend, so connections are reused. bearer_authadds theAuthorization: Bearerheader, and.json()setsContent-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.codeanderror.error_data.details. Meta says to build error handling on the code, since the titles inmessagewill 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:
| Line | src/main.rs |
|---|---|
| 18 | async fn send_examples(wa: &WhatsApp) -> Result<(), SendError> { |
| 19 | let 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."}}); |
| 20 | println!("text sent: {}", wa.send(&text).await?); |
| 21 | let params = json!([{"type": "text", "text": "Priya"}, {"type": "text", "text": "ORD-1042"}]); |
| 22 | let template = json!({"messaging_product": "whatsapp", "recipient_type": "individual", "to": "919800000000", "type": "template", "template": {"name": "order_update", "language": {"code": "en"}, "components": [{"type": "body", "parameters": params}]}}); |
| 23 | println!("template sent: {}", send_with_retry(wa, &template).await?); Ok(()) } |
tois 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:
| Code | Meaning | What your Rust code should do |
|---|---|---|
| 190 | Access token expired | Stop and alert; retrying won’t help. Use a permanent system-user token |
| 131047 | More than 24 hours since the customer last replied | Send an approved template instead |
| 132001 | Template doesn’t exist in that language or isn’t approved | Fix the name or language code; don’t retry |
| 130429 | Cloud API throughput reached | Wait and retry, with a growing delay |
| 131056 | Too many messages to the same person in a short time | Returned 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 80007 | App or WhatsApp Business Account API rate limit | Slow 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:
| Line | src/main.rs |
|---|---|
| 24 | async fn send_with_retry(wa: &WhatsApp, payload: &Value) -> Result<String, SendError> { |
| 25 | let mut delay = Duration::from_secs(1); |
| 26 | for attempt in 1..=4 { match wa.send(payload).await { |
| 27 | Err(SendError::Meta { code: 130429, .. }) if attempt < 4 => { tokio::time::sleep(delay).await; delay *= 2; } |
| 28 | other => return other, } } |
| 29 | unreachable!("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:
| Line | src/main.rs |
|---|---|
| 30 | type HmacSha256 = Hmac<Sha256>; |
| 31 | struct AppState { verify_token: String, app_secret: String } |
| 32 | async fn verify(State(s): State<Arc<AppState>>, Query(q): Query<HashMap<String, String>>) -> Result<String, StatusCode> { |
| 33 | let 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); |
| 34 | if ok { Ok(q.get("hub.challenge").cloned().unwrap_or_default()) } else { Err(StatusCode::FORBIDDEN) } } |
| 35 | fn valid_signature(secret: &str, body: &[u8], header: Option<&str>) -> bool { |
| 36 | let Some(hex_sig) = header.and_then(|h| h.strip_prefix("sha256=")) else { return false }; |
| 37 | let Ok(sig) = hex::decode(hex_sig) else { return false }; |
| 38 | let Ok(mut mac) = HmacSha256::new_from_slice(secret.as_bytes()) else { return false }; |
| 39 | mac.update(body); mac.verify_slice(&sig).is_ok() } |
| 40 | async fn receive(State(s): State<Arc<AppState>>, headers: HeaderMap, body: Bytes) -> StatusCode { |
| 41 | let sig = headers.get("x-hub-signature-256").and_then(|v| v.to_str().ok()); |
| 42 | if s.app_secret.is_empty() || !valid_signature(&s.app_secret, &body, sig) { return StatusCode::UNAUTHORIZED; } |
| 43 | tokio::spawn(handle(body)); StatusCode::OK } |
| 44 | async fn handle(body: Bytes) { let Ok(update) = serde_json::from_slice::<Value>(&body) else { return }; |
| 45 | for entry in update["entry"].as_array().into_iter().flatten() { for change in entry["changes"].as_array().into_iter().flatten() { let value = &change["value"]; |
| 46 | for m in value["messages"].as_array().into_iter().flatten() { println!("message {} from {}: {}", m["id"], m["from"], m["text"]["body"]); } |
| 47 | for st in value["statuses"].as_array().into_iter().flatten() { println!("status {}: {}", st["id"], st["status"]); } } } } |
- Handshake (lines 32 to 34): Meta sends
hub.mode=subscribe, your verify token and a randomhub.challenge. Return the challenge with a 200; Meta sends nothing until this passes. - Signature (lines 35 to 39): the header is
sha256=plus the hex HMAC-SHA256 of the raw body, keyed with your app secret.verify_slicecompares the tags in constant time (thedigestcrate usesct_eq), so don’t compare strings with==yourself. - Raw bytes first (line 40):
Bytesmust be the last extractor, because it reads the body. Check the signature on those exact bytes, then parse. - 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
| Line | src/main.rs |
|---|---|
| 48 | #[tokio::main] async fn main() { |
| 49 | if env::args().nth(1).as_deref() == Some("send") { if let Err(e) = send_examples(&WhatsApp::from_env()).await { eprintln!("send failed: {e:?}"); } return; } |
| 50 | let state = Arc::new(AppState { verify_token: env::var("VERIFY_TOKEN").unwrap_or_default(), app_secret: env::var("APP_SECRET").unwrap_or_default() }); |
| 51 | let app = Router::new().route("/webhook", get(verify).post(receive)).with_state(state); |
| 52 | let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap(); axum::serve(listener, app).await.unwrap(); } |
- Send:
cargo run -- sendwith the four variables set sends the text and the template to your test number and prints both message IDs. - Handshake: start the server with
cargo run, thencurl "localhost:8080/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=12345"should print12345. A wrong token gives 403. - Signed POST: set
BODY='{"entry":[]}'andSIG=$(printf %s "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}'), thencurl -i -X POST -H "X-Hub-Signature-256: sha256=$SIG" -d "$BODY" localhost:8080/webhookshould return 200. Change one body character: 401. - Go live: run
cargo build --release, deploy behind a public HTTPS address with a valid certificate (Meta doesn’t accept self-signed ones), savehttps://your-domain/webhookand 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
- Meta: Send messages
- Meta: Templates overview
- Meta: Create a webhook endpoint
- Meta: Throughput
- Meta: Error codes
- Meta: Graph API changelog
- docs.rs: reqwest
- 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.


