Outside the Box – Using Web Services from Python
I’ve been trying to learn more about things like web services and APIs provided by internet companies (gotta figure out what all of these buzzwords are.) One thing I’ve noticed is that many companies now provide a REST API which return JSON objects. There are enough resources on the web that describe REST and JSON that I don’t need to repeat it here; I’m just going to get to my python experiments on this technology.
So what does it do?
The python script uses the Google Translate API to translate text from one language to another. Maybe not the most useful new tool for Rhino, but it shows how simple it is to format a request to a web service and get at the results.
Some important things to note:
- The scripts in both attachments are exactly the same. There is code in the script to figure out if it is running as a normal Rhino python script or inside of Grasshopper.
- The script does different things when it is running in Rhino versus when running in Grasshopper. In Rhino, the script converts text dot text which in Grasshopper the script uses input and output variables.
- I’m using the sticky variable to cache results. This way we don’t have to keep going out to Google if we are translating the same text over and over again
Search around on the internet for REST apis that return JSON data. Your python scripts that use these other services will end up looking pretty similar to the samples I posted (unless you don’t like my scripting style;)) Here are some interesting APIs to look at: