Automate your SEO audits with a single API call
This tutorial will guide you through automating your SEO audits using the Wingman Protocol API. We'll focus on a practical Python implementation that fetches comprehensive SEO data for a given URL with a single API call, and demonstrates how to handle responses and potential errors. This approach eliminates the need for multiple tools and manual checks, saving you significant time and effort.
Prerequisites:* Python 3.6 or higher installed. * A Wingman Protocol API key (sign up at api.wingmanprotocol.com).
Step 1: Install therequests library
The requests library is essential for making HTTP requests in Python. If you don't have it installed, use pip:
pip install requests
Step 2: Import necessary libraries
import requests
import json
Step 3: Define your API key and target URL
API_KEY = "YOUR_WINGMAN_PROTOCOL_API_KEY"
Step 4: Make the API request
The core of this tutorial is making the API request to Wingman Protocol. We'll use the /audit endpoint. The API returns a JSON response containing a wealth of SEO data.
def perform_seo_audit(url, api_key):
"""
Performs an SEO audit on the given URL using the Wingman Protocol API.
Args:
url (str): The URL to audit.
api_key (str): Your Wingman Protocol API key.
Returns:
dict: A dictionary containing the audit results, or None if an error occurred.
"""
endpoint = "https://api.wingmanprotocol.com/audit"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"url": url
}
try:
response = requests.post(endpoint, headers=headers, data=json.dumps(payload))
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
except json.JSONDecodeError as e:
print(f"Error decoding JSON response: {e}")
return None
Explanation:
* We define the API endpoint URL.
* We create headers including the Authorization header with your API key (using the Bearer token scheme) and the Content-Type header.
* We create a payload dictionary containing the url to be audited. This is converted to a JSON string using json.dumps().
* We use a try...except block to handle potential errors:
* requests.exceptions.RequestException catches network errors (e.g., connection refused, timeout).
response.raise_for_status() checks for HTTP error codes (4xx or 5xx) and raises an exception if one is encountered. This is crucial* for robust error handling.
* json.JSONDecodeError handles cases where the API returns invalid JSON.
* If the request is successful, we parse the JSON response using response.json() and return it. If any error occurs, we print an error message and return None.
Now, let's call the function and process the results.
if __name__ == "__main__":
audit_results = perform_seo_audit(TARGET_URL, API_KEY)
if audit_results:
print("SEO Audit Results:")
# Example: Print the title tag
print(f" Title Tag: {audit_results.get('title_tag', 'Not found')}")
# Example: Print the number of backlinks
print(f" Number of Backlinks: {audit_results.get('backlinks', {}).get('total', 'Not found')}")
#Example: Print Mobile Friendliness
print(f" Mobile Friendliness: {audit_results.get('mobile_friendliness', 'Not found')}")
# Access other data points as needed. Refer to the API documentation
# at https://api.wingmanprotocol.com/docs for a complete list of available data.
# Example: Print all keys in the results (for exploration)
# for key in audit_results:
# print(f" {key}: {audit_results[key]}")
else:
print("SEO audit failed. Check the error messages above.")
Explanation:
* The if __name__ == "__main__": block ensures that the code only runs when the script is executed directly (not when imported as a module).
* We call the perform_seo_audit function with the target URL and API key.
* We check if the audit_results are valid (not None).
* If the results are valid, we print them. The example shows how to access specific data points using the get() method, which safely handles cases where a key might be missing from the response. Using .get() with a default value ("Not found" in this case) prevents KeyError exceptions.
* The commented-out loop provides a way to explore all the data points returned by the API.
* Error Handling: Always include robust error handling, as demonstrated in the try...except block. This prevents your script from crashing and provides informative error messages.
* Rate Limiting: Be mindful of the API's rate limits. Wingman Protocol's documentation specifies these limits. Implement delays or queuing mechanisms to avoid exceeding them.
* Data Validation: While the API generally returns valid data, it's good practice to validate the data before using it in critical calculations or reports.
* API Key Security: Never hardcode your API key directly into your code if you're sharing it or committing it to a public repository. Use environment variables or a secure configuration file instead.
* Documentation: Refer to the official Wingman Protocol API documentation (https://api.wingmanprotocol.com/docs) for a complete list of available data points and their descriptions.
This tutorial provides a basic foundation for automating SEO audits with the Wingman Protocol API. Here are some ideas for expanding this functionality:
* Batch Audits: Modify the script to accept a list of URLs and perform audits in parallel. * Report Generation: Generate detailed SEO reports in formats like CSV, PDF, or HTML. * Integration with other tools: Integrate the API with other SEO tools or dashboards. * Automated Monitoring: Schedule the script to run regularly and monitor changes in SEO performance.
Ready to streamline your SEO workflow? Get your Wingman Protocol API key today at https://api.wingmanprotocol.com and start automating your audits!