Hey there, fellow code wranglers! Ready to dive into the world of WordPress API integration with Python? You're in for a treat. WordPress's API is a powerhouse, and when you pair it with Python's simplicity, you've got a match made in developer heaven. Let's cut to the chase and get your Python talking to WordPress like old friends.
Before we jump in, make sure you've got:
requests
library (pip install requests
)You're probably all set, but just in case, run a quick pip install requests
to cover your bases.
WordPress uses OAuth 2.0, which might sound fancy, but it's pretty straightforward. You'll need:
Head to your WordPress site, install the "Application Passwords" plugin if you haven't already, and generate these credentials. Keep them safe – they're your golden tickets.
Let's get our Python script ready to chat with WordPress:
import requests base_url = "https://your-wordpress-site.com/wp-json/wp/v2" headers = { "Authorization": "Bearer YOUR_ACCESS_TOKEN" }
Replace YOUR_ACCESS_TOKEN
with the real deal, and you're good to go.
Now for the fun part – let's CRUD it up!
response = requests.get(f"{base_url}/posts", headers=headers) posts = response.json() print(posts)
new_post = { "title": "Hello API World", "content": "This post was created via API. Neat, huh?", "status": "publish" } response = requests.post(f"{base_url}/posts", headers=headers, json=new_post) print(response.json())
updated_post = { "title": "Updated via API", "content": "This post has been updated. Technology is amazing!" } response = requests.put(f"{base_url}/posts/123", headers=headers, json=updated_post) print(response.json())
response = requests.delete(f"{base_url}/posts/123", headers=headers) print(response.status_code)
Got custom post types? No problem:
# Fetch custom post types response = requests.get(f"{base_url}/custom_post_type", headers=headers) custom_posts = response.json() # Create a custom post type new_custom_post = { "title": "New Custom Post", "content": "This is a custom post type entry.", "status": "publish" } response = requests.post(f"{base_url}/custom_post_type", headers=headers, json=new_custom_post)
Let's add some pizzazz with image uploads:
files = { 'file': open('awesome_image.jpg', 'rb') } response = requests.post(f"{base_url}/media", headers=headers, files=files) media_id = response.json()['id'] # Attach to a post updated_post = { "featured_media": media_id } requests.put(f"{base_url}/posts/123", headers=headers, json=updated_post)
Always be prepared:
try: response = requests.get(f"{base_url}/posts", headers=headers) response.raise_for_status() except requests.exceptions.HTTPError as err: print(f"Oops, something went wrong: {err}") # Basic rate limiting import time def rate_limited_request(url): response = requests.get(url, headers=headers) if response.status_code == 429: retry_after = int(response.headers.get('Retry-After', 5)) time.sleep(retry_after) return rate_limited_request(url) return response
Want to get fancy? Try these:
# Filtering and sorting params = { "categories": 5, "orderby": "date", "order": "desc", "per_page": 10, "page": 2 } response = requests.get(f"{base_url}/posts", headers=headers, params=params)
Here's a little script that ties it all together:
import requests import time base_url = "https://your-wordpress-site.com/wp-json/wp/v2" headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"} def rate_limited_request(method, url, **kwargs): response = method(url, **kwargs) if response.status_code == 429: retry_after = int(response.headers.get('Retry-After', 5)) time.sleep(retry_after) return rate_limited_request(method, url, **kwargs) return response # Fetch recent posts posts = rate_limited_request(requests.get, f"{base_url}/posts", headers=headers).json() # Create a new post new_post = { "title": "API Magic", "content": "Look ma, no hands!", "status": "publish" } created_post = rate_limited_request(requests.post, f"{base_url}/posts", headers=headers, json=new_post).json() # Upload and attach media with open('cool_pic.jpg', 'rb') as img: files = {'file': img} media = rate_limited_request(requests.post, f"{base_url}/media", headers=headers, files=files).json() updated_post = { "featured_media": media['id'] } rate_limited_request(requests.put, f"{base_url}/posts/{created_post['id']}", headers=headers, json=updated_post) print("All done! Check your WordPress site for the new post with an image.")
And there you have it! You're now armed and dangerous with WordPress API knowledge. Remember, with great power comes great responsibility – use your newfound skills wisely.
For more in-depth info, check out the official WordPress REST API Handbook. Now go forth and integrate!
Happy coding, you magnificent developer, you!