Azure Service Bus with Python REST API (No SDK)

Updated Last updated: April 7, 2026 · Originally published: April 23, 2022

Why Bypass the Azure SDK for Service Bus?

📌 TL;DR: Why Bypass the Azure SDK for Service Bus? Azure Service Bus is a solid messaging platform that supports reliable communication between applications and services.
🎯 Quick Answer: Send messages to Azure Service Bus without the SDK by making HTTP POST requests to https://.servicebus.windows.net//messages with a SAS token in the Authorization header. Generate the token using HMAC-SHA256 over the resource URI with your shared access key.

Azure Service Bus is a solid messaging platform that supports reliable communication between applications and services. While the official Python SDK simplifies interaction with Service Bus, there are compelling reasons to bypass it and directly interact with the REST API instead:

  • Minimal Dependencies: The SDK introduces additional dependencies, which can be problematic for lightweight environments or projects with strict dependency management policies.
  • Full HTTP Control: Direct API access allows you to customize headers, configure retries, and handle raw responses, giving you complete control over the HTTP lifecycle.
  • Compatibility with Unique Environments: Non-standard environments, such as some serverless functions or niche container setups, may not support the Azure SDK. The REST API ensures compatibility.
  • Deeper Insights: By working directly with the REST API, you gain a better understanding of how Azure Service Bus operates, which can be invaluable for debugging and advanced configurations.

While the SDK is a convenient abstraction, bypassing it offers granular control and greater flexibility. This guide will walk you through sending and receiving messages from Azure Service Bus using Python’s requests library, without relying on the Azure SDK. Along the way, you’ll learn to authenticate using Shared Access Signature (SAS) tokens, troubleshoot common issues, and explore advanced use cases for the Service Bus REST API.

Prerequisites: Setting Up for Success

Before diving into implementation, ensure you have the following:

  • Azure Subscription: Access to the Azure portal with an active subscription is required to provision and manage Service Bus resources.
  • Service Bus Namespace: Create a Service Bus namespace in Azure. This namespace serves as a container for your queues, topics, and subscriptions.
  • Queue Configuration: Set up a queue within your namespace. You will use this queue to send and receive messages.
  • Authentication Credentials: Obtain the SAS key and key name for your namespace. These credentials will be used to generate authentication tokens for accessing the Service Bus.
  • Python Environment: Install Python 3.6+ and the requests library. You can install the library via pip using pip install requests.
  • Basic HTTP Knowledge: Familiarity with HTTP methods (GET, POST, DELETE) and JSON formatting will make the process easier to understand.

Once you have these prerequisites in place, you’re ready to start building your Service Bus integration using the REST API.

Step 1: Generating a Shared Access Signature (SAS) Token

Authentication is a critical step when working with Azure Service Bus. To interact with the Service Bus REST API, you need to generate a Shared Access Signature (SAS) token. This token provides time-limited access to specific Service Bus resources. Below is a Python function to generate SAS tokens:

import time
import urllib.parse
import hmac
import hashlib
import base64

def generate_sas_token(namespace, queue, key_name, key_value):
 """
 Generate a SAS token for Azure Service Bus.
 """
 resource_uri = f"https://{namespace}.servicebus.windows.net/{queue}"
 encoded_uri = urllib.parse.quote_plus(resource_uri)
 expiry = str(int(time.time()) + 3600) # Token valid for 1 hour
 string_to_sign = f"{encoded_uri}\n{expiry}"
 key = key_value.encode("utf-8")
 signature = hmac.new(key, string_to_sign.encode("utf-8"), hashlib.sha256).digest()
 encoded_signature = base64.b64encode(signature).decode()

 sas_token = f"SharedAccessSignature sr={encoded_uri}&sig={encoded_signature}&se={expiry}&skn={key_name}"
 return {"uri": resource_uri, "token": sas_token}

Replace namespace, queue, key_name, and key_value with your actual Azure Service Bus details. The function returns a dictionary containing the resource URI and the SAS token.

Pro Tip: Avoid hardcoding sensitive credentials like SAS keys. Instead, store them in environment variables and retrieve them using Python’s os.environ module. This ensures security and flexibility in your implementation.

Step 2: Sending Messages to the Queue

Once you have a SAS token, sending messages to the queue is straightforward. Use an HTTP POST request to send the message. Below is an example implementation:

import requests

def send_message_to_queue(token, message):
 """
 Send a message to the Azure Service Bus queue.
 """
 headers = {
 "Authorization": token["token"],
 "Content-Type": "application/json"
 }
 response = requests.post(f"{token['uri']}/messages", headers=headers, json=message)

 if response.status_code == 201:
 print("Message sent successfully!")
 else:
 print(f"Failed to send message: {response.status_code} - {response.text}")

# Example usage
namespace = "your-service-bus-namespace"
queue = "your-queue-name"
key_name = "your-sas-key-name"
key_value = "your-sas-key-value"

token = generate_sas_token(namespace, queue, key_name, key_value)
message = {"content": "Hello, Azure Service Bus!"}
send_message_to_queue(token, message)

Ensure the message payload matches your queue’s expectations. For instance, you might send a JSON object or plain text depending on your application’s requirements.

Warning: Ensure your SAS token includes Send permissions for the queue. Otherwise, the request will be rejected with a 403 error.

Step 3: Receiving Messages from the Queue

Receiving messages from the queue involves using an HTTP DELETE request to consume the next available message. Here’s an example implementation:

def receive_message_from_queue(token):
 """
 Receive a message from the Azure Service Bus queue.
 """
 headers = {"Authorization": token["token"]}
 response = requests.delete(f"{token['uri']}/messages/head", headers=headers)

 if response.status_code == 200:
 print("Message received:")
 print(response.json()) # Assuming the message is in JSON format
 elif response.status_code == 204:
 print("No messages available in the queue.")
 else:
 print(f"Failed to receive message: {response.status_code} - {response.text}")

# Example usage
receive_message_from_queue(token)

If no messages are available, the API will return a 204 status code, indicating the queue is empty. Processing received messages effectively is key to building a solid messaging system.

Pro Tip: If your application needs to process messages asynchronously, use a loop or implement polling mechanisms to periodically check the queue for new messages.

Troubleshooting Common Issues

Interacting directly with the Service Bus REST API can present unique challenges. Here are solutions to common issues:

  • 401 Unauthorized: This error often occurs when the SAS token is improperly formatted or has expired. Double-check the token generation logic and ensure your system clock is accurate.
  • 403 Forbidden: This typically indicates insufficient permissions. Ensure that the SAS token has the appropriate rights (e.g., Send or Listen permissions).
  • Timeout Errors: Network issues or restrictive firewall rules can cause timeouts. Verify that your environment allows outbound traffic to Azure endpoints.
  • Message Size Limits: Azure Service Bus enforces size limits on messages (256 KB for Standard, 1 MB for Premium). Ensure your messages do not exceed these limits.

Exploring Advanced Features

Once you’ve mastered the basics, consider exploring these advanced features to enhance your Service Bus workflows:

  • Dead-Letter Queues (DLQ): Messages that cannot be delivered or processed are sent to a DLQ. Use DLQs to debug issues or handle unprocessable messages.
  • Message Sessions: Group related messages together for ordered processing. This is useful for workflows requiring strict message sequence guarantees.
  • Scheduled Messages: Schedule messages to be delivered at specific times, enabling delayed processing workflows.
  • Auto-Forwarding: Automatically forward messages from one queue or topic to another, simplifying multi-queue architectures.
  • Batch Operations: Improve performance by sending or receiving multiple messages in a single API call.

Quick Summary

  • Using the REST API for Azure Service Bus provides flexibility and control, especially in environments where SDKs are not feasible.
  • Authentication via SAS tokens is critical. Always ensure precise permissions and secure storage of sensitive credentials.
  • Efficient queue management involves retry mechanisms, error handling, and adherence to message size limits.
  • Advanced features like dead-letter queues, message sessions, and scheduled messages unlock powerful messaging capabilities for complex workflows.

Mastering the Azure Service Bus REST API lets you build highly scalable, efficient, and customized messaging solutions. By understanding the underlying mechanics, you gain greater control over your application’s communication infrastructure.

🛠 Recommended Resources:

Tools and books mentioned in (or relevant to) this article:

📋 Disclosure: Some links are affiliate links. If you purchase through these links, I earn a small commission at no extra cost to you. I only recommend products I have personally used or thoroughly evaluated.


📚 Related Articles

📊 Free AI Market Intelligence

Join Alpha Signal — AI-powered market research delivered daily. Narrative detection, geopolitical risk scoring, sector rotation analysis.

Join Free on Telegram →

Pro with stock conviction scores: $5/mo

Get Weekly Security & DevOps Insights

Join 500+ engineers getting actionable tutorials on Kubernetes security, homelab builds, and trading automation. No spam, unsubscribe anytime.

Subscribe Free →

Delivered every Tuesday. Read by engineers at Google, AWS, and startups.

Frequently Asked Questions

What is Azure Service Bus with Python REST API (No SDK) about?

Why Bypass the Azure SDK for Service Bus? Azure Service Bus is a solid messaging platform that supports reliable communication between applications and services.

Who should read this article about Azure Service Bus with Python REST API (No SDK)?

Anyone interested in learning about Azure Service Bus with Python REST API (No SDK) and related topics will find this article useful.

What are the key takeaways from Azure Service Bus with Python REST API (No SDK)?

While the official Python SDK simplifies interaction with Service Bus, there are compelling reasons to bypass it and directly interact with the REST API instead: Minimal Dependencies: The SDK introduc

📧 Get weekly insights on security, trading, and tech. No spam, unsubscribe anytime.

Also by us: StartCaaS — AI Company OS · Hype2You — AI Tech Trends