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.

Easy Python 3.8+ Aug 9, 2026 Automation & scripting 11 views 0 copies

Python code

23 lines
Python 3.8+
import 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

stdout
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

  1. Use `requests.post(webhook_url, json={'text': message})` if the third-party `requests` library is available
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.