Recently I made my "Python for Testers" course publicly available.
The reason being I want to show testers just how easy Python is to get started with and the cool stuff you can do with it.
One of those things is generating test data.
You know the thing most of us have a guilty conscience about.
Earlier today I saw Ulrika Malmgren (@Ulrikama) tweet about a swedish site "www.slumpa.net" (which translates to "randomize" in Swedish).
The site offers to generate a random person for you with social number, name, address, much more, and even a pretty picture of the person!
So naturally I had to try their API using Python.
It only takes three lines of code to retrieve the data, but I added a fourth to print some of the data as well.
import requests, json r = requests.get('http://www.slumpa.net/api/') data = json.loads(r.text) print data['name'] +' '+ data['lastname']
It even fits within a tweet!
For this code I used two libraries: "requests" and "json"
If you're going to do any type of HTTP requests, I strongly encourage you to look into "Requests" for Python, one of the best libraries for this type of things out there (I have upcoming posts about using requests and Python).
Requests is not part of the standard library but it's a snap to install it, and if you don't know how to, then look at the end of this article.
I also used the json library found in the standard library.
If you look at the second line you see I make a very simple call:
r = requests.get('http://www.slumpa.net/api/')
Which gets me the data (a JSON data blob) from the URL provided, in this case the API exposed by the site.
After that I use the JSON library in Python to take the data in the response and transform it into a JSON-object.
data = json.loads(r.text)
And as a final touch I print some of the fields returned in the response.
print data['name'] +' '+ data['lastname']
This code can then be used in your test data generating scripts to retrieve some random persons data, and as an added bonus it's a swedish person and not a standard-plain english type of person, so you might end up with some tasty "åäö" letters and other stuff to test your system.
Full JSON data blob returned by api
How to install requests on your system
You have different options when installing this library ranging from using "pip", "easy_install", or just downloading the source code and building it.
If you have pip or easy_install already available on your system go with that:
$ pip install requests
$ easy_install requests
But if you don't have these tools available it is just as easy to just download the source code found on their download page, extract the files and then from your command line navigating to the folder where you extracted the code and run:
python setup.py install
The instructions on how to install requests can be found here, along with some caveats and other stuff.