register_routing_callback

View as MarkdownOpen in Claude

Register a callback function for dynamic request routing. When a request arrives at the specified path, the callback inspects the POST body and decides whether to route the request to a different endpoint or let normal processing continue. This is primarily used for SIP-based routing where the destination depends on the incoming SIP URI.

An HTTP endpoint is automatically created at the specified path when the service starts. The callback receives the raw FastAPI Request object and the parsed request body as a dictionary.

The callback path is registered at the time of calling this method but the actual FastAPI route is created when serve() is called or when as_router() generates the router. Register all callbacks before starting the server.

Parameters

callback_fn
Callable[[Request, dict[str, Any]], Optional[str]]Required

A function that receives a FastAPI Request and the parsed JSON body as a dict. Return a route string to redirect the request (using HTTP 307 to preserve the POST method and body), or return None to continue with normal SWML document serving.

path
strDefaults to /sip

The URL path where this routing endpoint is created. The path is normalized to start with / and trailing slashes are stripped.

Returns

None


extract_sip_username (static method)

Static utility method that extracts the username portion from a SIP URI in the request body. Handles sip:username@domain, tel:+1234567890, and plain string formats in the call.to field.

Parameters

request_body
dict[str, Any]Required

The parsed JSON body from an incoming request. Expected to contain a call.to field with a SIP URI, TEL URI, or phone number string.

Returns

Optional[str] — The extracted username or phone number, or None if the call.to field is missing or cannot be parsed.

Example

Routing callback with SIP username

1from signalwire import SWMLService
2
3service = SWMLService(name="sip-router", route="/")
4
5def route_sip_call(request, body):
6 """Route calls based on the SIP username in the request."""
7 username = SWMLService.extract_sip_username(body)
8 if username == "sales":
9 return "/agents/sales"
10 elif username == "support":
11 return "/agents/support"
12 return None # Default handling
13
14service.add_verb("answer", {})
15service.register_routing_callback(route_sip_call, path="/sip")
16service.serve()

Extracting SIP usernames

1from signalwire import SWMLService
2
3body = {"call": {"to": "sip:sales@example.sip.signalwire.com"}}
4username = SWMLService.extract_sip_username(body)
5# "sales"
6
7body = {"call": {"to": "tel:+15551234567"}}
8number = SWMLService.extract_sip_username(body)
9# "+15551234567"