Hey there, fellow developer! Ready to dive into the world of SEMrush API integration? You're in for a treat. SEMrush's API is a powerhouse for SEO and marketing data, and we're going to harness that power using Python. We'll be using the semrush-cli
package, which makes our lives a whole lot easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that semrush-cli
package installed:
pip install semrush-cli
Easy peasy, right?
Now, let's set up our API key. You could hardcode it, but let's be smart about this:
import os from semrush.api import SemrushClient api_key = os.environ.get('SEMRUSH_API_KEY') client = SemrushClient(api_key)
Pro tip: Store your API key as an environment variable. Your future self will thank you!
Time to import our package and create a client instance:
from semrush.api import SemrushClient client = SemrushClient('your-api-key-here')
The semrush-cli
package gives us a bunch of methods to play with. Let's start with a Domain Overview report:
domain = 'example.com' result = client.domain_ranks(domain) print(result)
Boom! You've just made your first API request.
The API returns JSON data, which is super easy to work with in Python:
import json data = json.loads(result) print(data['organic']['traffic'])
Don't forget to handle those pesky errors:
try: result = client.domain_ranks(domain) except Exception as e: print(f"Oops! Something went wrong: {e}")
Ready to level up? Let's talk batch requests:
domains = ['example1.com', 'example2.com', 'example3.com'] results = client.domain_ranks_batch(domains)
Just remember, with great power comes great responsibility. Keep an eye on those rate limits!
Now that we've got our data, let's do something cool with it:
import pandas as pd df = pd.DataFrame(results) print(df['organic_traffic'].mean())
A couple of pro tips to keep in your back pocket:
And there you have it! You're now equipped to build a robust SEMrush API integration in Python. Remember, practice makes perfect, so don't be afraid to experiment and push the boundaries.
Want to dive deeper? Check out the SEMrush API documentation and the semrush-cli GitHub repo.
Now go forth and conquer the SEO world with your newfound powers!
Hit a snag? Here are a few common issues and their solutions:
Remember, every error is just a learning opportunity in disguise. Happy coding!