Trigger a Cloud Phone from a Webhook with FastAPI (2026)
A webhook fires, and you want a real Android phone to do something: open an app, tap a button, read a notification, grab a screenshot. The glue between “event arrived” and “phone did the thing” is a small service. FastAPI plus ADB is a clean way to build it, and it runs against a real cloud phone exactly as it would a local one.
I run a farm of real Android phones in Singapore, reachable over ADB, so this is the working version: receive a webhook, run an action on the device, return a result, with the queueing and security bits people skip until they get burned.
the shape of the thing
Three moving parts:
- FastAPI receives the webhook over HTTPS and validates it.
- A worker runs the ADB command against the cloud phone. ADB is single-threaded per device, so this goes through a queue, not straight off the request.
- The cloud phone does the work and reports back.
The reason for the queue is simple. A phone can do one thing at a time. If two webhooks land at once and both fire ADB commands at the same device, they stomp on each other. So the web layer accepts fast and a worker drains the queue serially.
connect to the phone over ADB
With cloudf.one you reach the device over the network:
adb connect <phone-host>:<port>
adb devices
# 100.x.y.z:5555 device
That adbName, 100.x.y.z:5555, is what every command targets with adb -s.
the FastAPI service
Receive the webhook, verify it, enqueue the job, return immediately. Do not run ADB inside the request handler, because a slow device call would block the response and risk the sender timing out and retrying.
# app.py
import asyncio
import hashlib
import hmac
import os
import subprocess
from fastapi import FastAPI, Header, HTTPException, Request
app = FastAPI()
ADB_SERIAL = os.environ["ADB_SERIAL"] # e.g. 100.x.y.z:5555
WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"].encode()
# one worker drains this; the phone does one thing at a time
queue: asyncio.Queue = asyncio.Queue()
def verify_signature(body: bytes, signature: str) -> bool:
expected = hmac.new(WEBHOOK_SECRET, body, hashlib.sha256).hexdigest()
# constant-time compare so we do not leak timing
return hmac.compare_digest(expected, signature or "")
def run_adb(args: list[str], timeout: int = 30) -> str:
# never build the command from a shell string; pass a list
result = subprocess.run(
["adb", "-s", ADB_SERIAL, *args],
capture_output=True,
text=True,
timeout=timeout,
)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or "adb failed")
return result.stdout.strip()
async def worker():
while True:
job = await queue.get()
try:
# run blocking ADB off the event loop
await asyncio.to_thread(handle_job, job)
except Exception as e:
print(f"job {job} failed: {e}")
finally:
queue.task_done()
def handle_job(job: dict):
action = job.get("action")
if action == "open_app":
pkg = job["package"]
run_adb(["shell", "monkey", "-p", pkg, "-c",
"android.intent.category.LAUNCHER", "1"])
elif action == "tap":
run_adb(["shell", "input", "tap", str(job["x"]), str(job["y"])])
elif action == "screenshot":
run_adb(["exec-out", "screencap", "-p"]) # bytes; route to storage
else:
raise ValueError(f"unknown action: {action}")
@app.on_event("startup")
async def startup():
asyncio.create_task(worker())
@app.post("/webhook")
async def webhook(request: Request, x_signature: str = Header(default="")):
body = await request.body()
if not verify_signature(body, x_signature):
raise HTTPException(status_code=401, detail="bad signature")
payload = await request.json()
# accept fast, do the work async
await queue.put(payload)
return {"status": "queued"}
Run it behind a real ASGI server:
ADB_SERIAL=100.x.y.z:5555 WEBHOOK_SECRET=your-shared-secret \
uvicorn app:app --host 0.0.0.0 --port 8000
why the queue matters
ADB has one connection to the device and the phone has one screen. If you fire input tap from two requests at the same instant, you get races: one tap lands on the wrong screen because the other action moved it. Serializing through a single worker means each job sees a known state. If you need throughput, do not parallelize against one phone. Connect more phones and run one worker per ADB_SERIAL.
For anything beyond a toy, swap the in-memory asyncio.Queue for a real broker (Redis, or a Celery/RQ worker) so jobs survive a restart and you can scale workers per device. The in-memory queue loses jobs if the process dies mid-drain.
security, because this is a remote-control endpoint
A webhook that taps a phone is a remote-control endpoint. Lock it down.
- Verify the signature. The
verify_signaturecheck above uses HMAC with a shared secret and a constant-time compare. Most webhook providers sign their payloads; verify against the raw body, never the parsed JSON, because reserialization changes bytes. - HTTPS only. Terminate TLS at a reverse proxy (Caddy or nginx) in front of uvicorn. Never take a signed secret over plain HTTP.
- Never shell-interpolate the payload. Notice
run_adbtakes a list and there is noshell=True. If you ever build an ADB string from webhook input with string formatting, you have handed the sender a shell on your host. Pass args as a list, always. - Allowlist actions.
handle_jobdispatches on a fixed set of actions and raises on anything else. Do not let the webhook name an arbitrary command to run. - Rate limit and timeout. Cap how often the endpoint accepts work and put a timeout on every ADB call so a hung device cannot wedge the worker forever. The
timeout=30onsubprocess.rundoes this per command.
test it
With the service running and a phone connected:
SECRET=your-shared-secret
BODY='{"action":"open_app","package":"com.android.settings"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')
curl -X POST http://localhost:8000/webhook \
-H "Content-Type: application/json" \
-H "X-Signature: $SIG" \
-d "$BODY"
# {"status":"queued"}
If Settings opens on the phone a moment later, the whole chain works: webhook in, signature verified, job queued, worker drained it, ADB drove the device.
where this runs best
This pattern is only as trustworthy as the phone behind it. On an emulator, the actions work but the device fingerprint and network are synthetic, so anything that touches a real app or a real network behaves differently than production. On a real cloud phone, the same webhook drives a genuine device on a real carrier IP, so an automation that opens an app, reads a notification, or posts something behaves like a real user did it.
cloudf.one gives you that real Android phone in Singapore over ADB, on a real SG mobile carrier IP, with no device lab to run. Point ADB_SERIAL at it and the service above works unchanged.
There is a free trial on the cloudf.one home page if you want to wire a webhook to a real phone and watch it react. Use code YT30 if you came from the channel.
frequently asked questions
why not run ADB directly in the FastAPI request handler? because a device call is slow and the phone does one thing at a time. running it in the handler blocks the response and risks the sender timing out and retrying, firing the action twice. accept fast, queue, and drain with a worker.
how do I handle several phones?
run one worker per device, each with its own ADB_SERIAL, and route jobs to the right queue. do not parallelize commands against a single phone.
is the in-memory queue safe for production? no. it loses jobs if the process restarts mid-drain. use Redis or Celery/RQ so jobs persist and workers scale per device.
what is the single biggest security mistake here?
building the ADB command from webhook input with string formatting and shell=True. that hands the sender a shell on your host. always pass args as a list and verify the signature against the raw body first.
Get new guides and videos first — join the Telegram channel.