Post a message to a Slack webhook in Python
Send a message to a Slack webhook endpoint using the standard library's urllib.request, handling the POST request and response cleanly.
Python code
23 linesimport json
from urllib import request
def post_to_slack(webhook_url: str, message: str) -> dict:
payload = json.dumps({"text": message}).encode("utf-8")
req = request.Request(
webhook_url,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
with request.urlopen(req) as response:
status = response.status
body = response.read().decode("utf-8")
return {"status": status, "body": body}
if __name__ == "__main__":
result = post_to_slack(
webhook_url="http://localhost:8000/mock-slack",
message="Hello from Python!",
)
print(f"Status: {result['status']}")
print(f"Response: {result['body']}")
Output
Status: 200
Response: ok
How it works
The code uses urllib.request from the standard library, so no external dependencies are needed. It converts the message to a JSON-encoded bytes object with json.dumps and .encode('utf-8'), then sends it as the request body with a Content-Type: application/json header. Request with method='POST' explicitly sets the HTTP method. The response status and body are captured inside a with block, ensuring the connection is closed properly. The function returns a dictionary with the response status and body, which is useful for logging or error handling.
Common mistakes
- Forgetting to encode the payload to bytes with `.encode('utf-8')`
- Not setting `Content-Type: application/json` header, causing errors in the webhook receiver
- Handling the response outside the `with` block, leading to potential connection issues
Variations
- Use `requests.post(webhook_url, json={'text': message})` if the third-party `requests` library is available
- Use `urlopen` without an explicit method, but set the payload to trigger POST automatically
Real-world use cases
- Send a notification to a Slack channel when a CI/CD pipeline job fails or completes.
- Alert on-call engineers about production incidents or high error rates via a Slack webhook.
- Post test results or daily reports from an automated monitoring or data-processing script.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.