Need help making a Python Wrapper for your REST API? Python is my personal favorite programming language. So when somebody approaches me with a problem that involves a REST API, I immediately go to Python. That being said, calling REST API’s can unfortunately be a little ugly in the language. I’ll show you how to turn an ugly multi line API call into a beautiful and efficient one.
- Python 3.x
- Windows 10 Pro
Without A Wrapper
Wrapper’s simplify code and make calling consistently used APIs more intuitive. That being said, if you only need to call an API once then I would personally avoid the extra work. This is how we’d call an API without spending the time on a wrapper. We’ll be using the Google Translate API for this example. You can find some relevant info here.
import requests response = requests.get('https://translation.googleapis.com/language/translate/v2/languages?key=YOUR_KEY_HERE') info = response.json()
So it’s all around just ugly in my opinion. The URL is too long and your key is everywhere.
Making a Python Wrapper for your REST API
import requests class Translate(): def __init__(self, api_key): session = requests.Session() self.session = session self.key=api_key def get_languages(self): response = requests.get('https://translation.googleapis.com/language/translate/v2/languages?key='+self.key) info = response.json() return info
Using the Wrapper
So we created a translate class. Lets create a translate object and pull the associated languages using the following.
translate = Translate('API_KEY') translate.get_languages()
It’s short and clean. It’s straight to the paint. Do you need all the languages? Call the get_languages method on the translate object and you’re done! Happy coding!