from flask import Flask, jsonify, request import requests from requests.auth import HTTPBasicAuth import json app = Flask(__name__) # WordPress REST API details wordpress_url = 'https://your-wordpress-site.com/wp-json/wp/v2/posts' wp_username = 'your_wp_username' wp_application_password = 'your_application_password' # External API details (Replace with the actual API endpoint and key) external_api_url = 'https://api.example.com/data' external_api_headers = { 'X-RapidAPI-Key': 'your-rapidapi-key', # Replace with your actual API key 'Content-Type': 'application/json' } # Function to fetch data from the external API def fetch_external_data(): response = requests.get(external_api_url, headers=external_api_headers) if response.status_code == 200: return response.json() # Return the JSON response from the API else: print(f"Error fetching external data: {response.status_code}") return None # Function to post data to WordPress def post_to_wordpress(title, content): post_data = { 'title': title, 'content': content, 'status': 'publish' # Change to 'draft' if you want to review posts first } response = requests.post( wordpress_url, auth=HTTPBasicAuth(wp_username, wp_application_password), headers={'Content-Type': 'application/json'}, data=json.dumps(post_data) ) if response.status_code == 201: return {'status': 'success', 'message': f"Post '{title}' successfully created!"} else: return {'status': 'error', 'message': response.content.decode()} # Flask route to trigger fetching from external API and posting to WordPress @app.route('/api/fetch_and_post', methods=['GET']) def fetch_and_post(): external_data = fetch_external_data() if external_data: results = [] # Loop through external data and post to WordPress for item in external_data: # Adjust based on API response structure title = item.get('title') # Replace with the appropriate field content = item.get('description') # Replace with the appropriate field # Post the data to WordPress result = post_to_wordpress(title, content) results.append(result) return jsonify(results) else: return jsonify({'status': 'error', 'message': 'Failed to fetch external data'}), 500 if __name__ == '__main__': app.run(debug=True)