How to Cross Post Markdown to dev.to API in Python
A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.
Python code
43 linesimport json
from urllib import request, error
def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
"""
Mock cross-posting of markdown content to the dev.to API.
Returns the API response or an error message.
"""
payload = json.dumps({
"article": {
"title": "My Cross-Posted Article",
"body_markdown": markdown_content,
"published": True,
"tags": ["python", "markdown"]
}
}).encode("utf-8")
req = request.Request(
devto_api_url,
data=payload,
headers={
"Content-Type": "application/json",
"api-key": api_key
},
method="POST"
)
try:
with request.urlopen(req) as response:
return json.loads(response.read().decode("utf-8"))
except error.HTTPError as e:
return {"error": f"HTTP {e.code}: {e.reason}"}
except error.URLError as e:
return {"error": f"Connection failed: {e.reason}"}
if __name__ == "__main__":
sample_markdown = "# Hello World\n\nThis is a test post.\n\n- Item 1\n- Item 2"
api_key = "test_api_key_12345"
# Using a non-existent host to demonstrate the error handling without real API calls
result = cross_post_to_devto(sample_markdown, api_key, "https://mock.invalid/api/articles")
print(result)
Output
{'error': 'Connection failed: <urlopen error [Errno -2] Name or service not known>'}
How it works
The function builds a JSON payload with the article title, markdown body, publication status, and tags, then sends it via urllib's Request object. Using the 'api-key' header authenticates with dev.to. The try/except block gracefully handles both HTTP errors and connection failures, returning a dictionary with the error details. The mock URL demonstrates error handling without making real API calls.
Common mistakes
- Forgetting to set the Content-Type header to 'application/json'
- Using the wrong API key header name (should be 'api-key' not 'Authorization')
- Not encoding the JSON payload to UTF-8 before posting
- Overlooking that dev.to expects the article data wrapped inside an 'article' key
Variations
- Use the requests library's post() method with json parameter for simpler syntax
- Add support for sets of tags and optional fields like canonical_url or description
Real-world use cases
- A blogging automation script that publishes content to dev.to and Medium simultaneously.
- A CI/CD pipeline that cross-posts release notes to dev.to after each deployment.
- A content migration tool that imports markdown files from a git repo and publishes them to dev.to.
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.