From Postman to Python: Your First GET Request (2022)

Maybe it's just me - but I feel like when we want to demonstrate product APIs to someone, we usually jump into Postman first. It's not without good reason though. Postman is a very easy to use platform for running API calls against REST endpoints & see the nicely formatted output.

That being said, often times I've seen that we stop there. We might mention Python as an advanced method of using our APIs, or maybe we talk about how "if APIs are the new CLI, Postman is the new PuTTY". I've seen some engineers who hear these statements and feel like Postman is being pushed on them - even when they're perfectly happy with an SSH-based CLI.

Network automation isn't usually accomplished with just one tool - it's a whole storage closet full of different tools & utilities, each with their own use cases or specializations. In this particular example - learning Python allows you to move beyond one-off API calls in Postman, and into being able to accomplish much more complex automation.

So the purpose of this post is to explore how to get beyond just Postman, and into using Python for REST API calls. This isn't going to be a complete run-down of all the capabilities of both tools - but rather a few examples of simple GET requests using both methods.

If you don't have Postman yet, go ahead and snag the download here.

Note: Much of the code below is minimal and does not contain any error handling. Therefore, it should not be used in a production network. Full example code here.

Postman: Simple GET Request

So first, let's start off with an example of using Postman for a simple GET request.

In this example, we'll keep things simple & use a non-authenticated API endpoint. We'll accomplish this using a free website called JSON Placeholder.

Let's go ahead and start up Postman, and we'll see a blank workspace:

From Postman to Python: Your First GET Request (1)

What we'll need to pay attention to first, is what type of HTTP request we're sending - as well as the URL we want to send our request to. If we expand the request type dropdown, we'll see a handful of options - but we'll only be using a GET request for now:

From Postman to Python: Your First GET Request (2)

In order to create our first request, we'll just need to enter our API endpoint URL. We'll use the users endpoint offered by JSON Placeholder, which is located at: https://jsonplaceholder.typicode.com/users

From Postman to Python: Your First GET Request (3)

(Video) From Postman to Python: Your First GET Request

In the screenshot above, you'll see in the highlighted box that we entered our URL. Next, we just click the big Send button on the right side.

I already sent the GET request, so in the screenshot you'll also notice that we have our JSON response from the API. The mock data offered by this API provides us with a list of 10 different users, along with the data that's been entered for each user.

What if we only wanted to get data for one specific user? Well, our test API site supports using query parameters to filter our response. Let's say we want to find information for a user named Delphine. We would append ?username=Delphine to our URL:

From Postman to Python: Your First GET Request (4)

So as we can see above - now our JSON response only contains the data for a single user. If we needed to find a user's phone number, this could be an easy way to quickly filter our data & get to what we need.

This is really where Postman is great. We're able to quickly & visually test out an API call. We can see what the response data looks like, and understand the structure of requests & responses.

But what about when we want to iterate through a number of users and pull only a specific few statistics? Or maybe we need a way to take a list of user information, and automatically upload or convert that data into another system.

For use cases like that, we'll jump over to Python.

Python: Simple GET Request

In this section, we'll walk through the same example from above - but this time using Python.

First thing we'll need to do, is install the Python requests library. While there are a handful of libraries that can accomplish this work, requests is fairly popular & easy to use.

So we'll kick things off by using pip to install our library:

pip install requests

Then, we'll create a very simple Python script to perform the same initial GET request from earlier. So we'll pull a list of ALL users from the API.

import requestsURL = "https://jsonplaceholder.typicode.com/users"response = requests.get(URL)print(response.text)

The code above should be pretty straightforward. First we'll import our requests library. Then, just to keep the code clean, we'll create a variable called URL to hold the URL for the API endpoint.

(Video) Python Requests | Get and Post Requests

Next, we send that GET request, using requests.get. Last but not least, we'll go ahead and print out the text payload that we receive back. That output looks pretty similar:

[emailprotected]:~/postman-python$ python3 simpleGET.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[emailprotected]", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { -- output truncated -- 

Now, let's add a little extra logic to our next step. Rather than just specifying a static username that we want to search for, let's ask our user to specify a username:

import requestsURL = "https://jsonplaceholder.typicode.com/users"print("Search by Username:")user = input("> ")queryURL = URL + f"?username={user}"response = requests.get(queryURL)print(response.text)

In the code above, we made just a few changes. One is printing out a prompt to "Search by Username". Then we use the Python input function to collect input from our user, then store that in the user variable.

Next, we create a queryURL - which is similar to the URL we used in the Postman example. Except in this case, we're supplying a dynamic username input based on whatever the end user wants to search for. We use a Python f-string to inject the username into our query parameters.

Let's see what that looks like:

[emailprotected]:~/postman-python$ python3 simpleGET.py Search by Username:> Delphine[ { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "[emailprotected]", "address": { "street": "Dayna Park", "suite": "Suite 449", "city": "Bartholomebury", "zipcode": "76495-3109", "geo": { "lat": "24.6463", "lng": "-168.8889" } }, "phone": "(775)976-6794 x41206", "website": "conrad.com", "company": { "name": "Yost and Sons", "catchPhrase": "Switchable contextually-based project", "bs": "aggregate real-time technologies" } }]

Perfect! We get the result we expected, which is the single dataset from the user that we specified.

Let's take this one step further! Maybe we want to build a quick utility to search for a user's contact information. We can take the raw JSON output, pull out a few pieces of info, then apply some formatting to make it more user-friendly.

In the following example, we'll update our code to search that JSON response & collect the user's name, email address, and phone number.

import requestsimport jsonURL = "https://jsonplaceholder.typicode.com/users"print("Search by Username:")user = input("> ")queryURL = URL + f"?username={user}"response = requests.get(queryURL)userdata = json.loads(response.text)[0]name = userdata["name"]email = userdata["email"]phone = userdata["phone"]print(f"{name} can be reached via the following methods:")print(f"Email: {email}")print(f"Phone: {phone}")

So a few things have changed in the above example. First thing you may notice, is that we've added an additional import: the json library. We use this in line 11, where we convert the JSON output into a native python object using the json.loads function.

What this allows us to do is easily pull individual data values from the JSON output. In the original JSON data that we received, we saw a bunch of user data organized into key-value pairs. So once we load that JSON into a Python dictionary, we can pull out individual values and assign them to variables.

Finally - we can print all of that data out to our terminal:

[emailprotected]:~/postman-python$ python3 simpleGET.pySearch by Username:> DelphineGlenna Reichert can be reached via the following methods:Email: [emailprotected]Phone: (775)976-6794 x41206

Nothing super fancy here - but this could be the beginnings of building out a user search web page, or maybe importing certain data fields into another system. Once we get the basics of working with REST APIs out of the way, there are a ton of possibilities for what can be built.

Okay - What About Network Automation?

Many new network technologies are now API enabled. Nearly every cloud-hosted platform or management controller offers some method of interacting programmatically. In fact, most routers & switches even offer a REST-based API that can be used for automated configuration or monitoring.

(Video) Postman API for Python

So let's take the following example: We have a couple of Meraki networks, and we've been tasked with providing a report of how many total clients have connected to our network in the last 30 days. In addition, it would be nice to see a breakdown of the distribution of operating systems.

Let's take a look at the following screenshot from Postman:

From Postman to Python: Your First GET Request (5)

Using Meraki's API docs, we can determine the exact URL endpoint we need to query. This URL requires that we know the exact network ID for the network we want to get info from, which we'll pretend we already know. Also not shown here, we have an additional HTTP header that includes our API key - which was generated in Meraki Dashboard.

In addition, we have a few query parameters to help make sure we get the data we need. By default, this API endpoint will return 10 devices. In this particular network, we already know we have more than 10 - so we use the perPage query parameter to request up to 100 devices. We also wanted to query the last 30 days of devices, so we use the timespan parameter. This parameter expects the lookback to be in seconds, so we specify 43,200 seconds.

So we got back a list of devices - and specifically in the example shown, it looks like we have an Android device on our network. Easy enough to spot that info, right?

Well - maybe we have more than a handful of devices. We don't want to manually sort through all of that data & assemble a list. Or maybe this task needs to be run more than once. This is where we can use Python to automatically assemble that report with just a few lines of code.

import requestsimport jsonURL = "https://api.meraki.com/api/v1"APIKEY = {"X-Cisco-Meraki-API-Key": "xxxxxxxxxxxxxxxxx"}--- Code omitted ---def getClients(orgID, networkList): """ Query clients for each network, return client list """ clientCount = {} total = 0 # Query Parameters: Return up to 100 devices seen in the past 43,200 seconds (30 days) q = {"perPage": "100", "timespan": "43200"} for network in networkList: # Query clients for each network queryURL = URL + f"/networks/{network}/clients" response = requests.get(queryURL, params=q, headers=APIKEY) data = json.loads(response.text) # Grab client OS from each device & append to clientCount dictionary for client in data: try: clientCount[client["os"]] += 1 except KeyError: clientCount[client["os"]] = 1 except TypeError: continue total += 1 # Append final count of all devices & return dict clientCount["Total Devices"] = total return clientCountdef printReport(clientOS): """ Print final output to terminal """ print("Count of clients by operating system:") for OS in clientOS: print(f"{OS}: {clientOS[OS]}") --- Code omitted --- 

To keep things simple - we'll only look at a snippet of the code. The entire example will be posted to GitHub, and contains two additional functions that will automatically find our Organization ID & Network ID.

In our getClients function, we create an empty Python dictionary to hold our list of client operating systems - and we also create a total variable which we'll increment for every client in the list.

The HTTP GET request should look fairly similar to what we used previously. The big difference is that we're creating a dictionary called q to hold our perPage & timespan query parameters. Then we include that in our GET request by adding params=q to the request.

Next - we convert the JSON response into a Python object, and walk through every device in that list. For each device in the list, we look at the "os" value to determine the operating system detected by Meraki. We then use a try/except block to see if we can increment the counter for that operating system. If we get a KeyError, then we know the OS isn't currently on the list & we can just add it with a new value of 1.

After all that has been completed, we return our clientCount dictionary - which our primary function passes to the printReport function. This just prints out a header, then iterates through our clientCount dictionary and prints each operating system & count.

Let's take a look at that output below:

(Video) Tut#25 | Python & MySQL | postman | api | python tutorial

[emailprotected]:~/postman-python$ python getOScount.pyCount of clients by operating system:None: 9Sailfish OS: 2Nokia: 1Windows 10: 2Raspberry Pi: 2Android: 4Meraki OS: 1Total Devices: 21

In the list above, we can see that we have a total of 21 devices in our network - and 7 different operating systems were found as well.

That output may not be the prettiest of reports, but it was accomplished with ~50 lines of Python & takes less than a few seconds to run. If we wanted to format the data in another way, or include data from a non-Meraki source, we absolutely could.

That's part of what's exciting about using Python for network automation - most anything we could think of doing is possible.

TIP: Use Postman to Generate Python Code

Okay - so I wanted to save this bit for last. Now that you've seen examples in both tools, I wanted to make sure we cover a feature in postman that can save some time.

So over in the right-hand side of your Postman window, you'll see an icon that looks like this: </>

From Postman to Python: Your First GET Request (6)

If you click that, you'll see a dropdown menu of various languages & tools. Select one of those options and Postman will auto-generate code you can use. This auto-generated code will execute the same request you have built in the Postman GUI.

For example, our last Postman request we used to get Meraki clients:

From Postman to Python: Your First GET Request (7)

I wanted to save this for last, because I feel like it's important to understand how to write the code manually first - then take advantages of shortcuts after having a good understanding of what the code is doing.

That's about all I had for this example. Again, my intent here wasn't to create an all-inclusive resource for how to use Postman & Python - but rather to give some examples for each one & show where/why each would be used.

I've met a handful of people over the years who have seen many API demos using Postman, but aren't sold yet on the value of learning Python & getting into network automation.

Hopefully these examples help bridge that gap a little bit 😄

(Video) Postman and Python - Capturing HTTP requests (Use case)

FAQs

How do I convert Postman request to Python? ›

The first step is to setup your request the way you want it. That means the type (eg, GET), the URL, headers, body, authorization, and whatever else you need. Over on the far right of the screen there's a toolbar with a Code Snippet button (</>). Once you click that, you can select the language that you want.

How do you get the Postman request body in Python? ›

From Postman to Python: Your First GET Request - YouTube

Can we use Postman with Python? ›

As an example, you can use Postman to generate Python code for the call that shuffles six decks, then have the Python code use that generated deck_id to draw two cards from the deck.

How do you automate Postman API in Python? ›

Automate your API tests with Postman
  1. Understand the API. Explore API Doc → Import API specification. ...
  2. Build test suite. Write and run individual tests Doc → Verify in Postman Collection Runner. ...
  3. Work and verify with your team. Invite teammates to a workspace. ...
  4. Integrate with DevOps lifecycle. Export test suite.

How do I export a Postman request? ›

You can export a data dump of all your collections, environments, globals, and header presets in Postman. in the header, then select Settings. Select the Data tab, then Export Data to start your request for the data dump. Select Export Data to confirm the data types you need to export.

How do I send a body in GET request? ›

So, yes, you can send a body with GET, and no, it is never useful to do so. This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress). Yes, you can send a request body with GET but it should not have any meaning.

How do you check GET method in Postman? ›

You can enter these details into the Postman application:
  1. Select the GET method.
  2. Click on "Params" to add URL query params.
  3. Enter the key-value pair for the auth_token query param. It will then appear in the URL input.
  4. Click on "Send" the run the HTTP request.
Sep 14, 2018

How do I send Postman request in JSON? ›

POST requests

In Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.

What is in a GET request? ›

A GET request, in simple terms, is a way for you to grab data from a data source with the help of the internet. It's done using the GET request method, which is a very common HTTP request method (like POST, PUT, or DELETE). Despite the capitalization, “GET” is not an acronym, so it doesn't stand for anything.

How do you call an API in Python? ›

Make your API call
  1. def get_data(self, api):
  2. response = requests.get(f"{api}")
  3. if response.status_code == 200:
  4. print("sucessfully fetched the data")
  5. self.formatted_print(response.json())
  6. else:
  7. print(f"Hello person, there's a {response.status_code} error with your request")

How do I get response from API to Postman? ›

All you have to do is call postman.
...
Extracting Data from Responses and Chaining Requests
  1. Send a request from Postman.
  2. Receive the response and select and copy a value from the response body or the header.
  3. Go to the environment manager.
  4. Set the variable value.
  5. Hit submit.
Jan 27, 2014

How do you automate REST API testing in Python? ›

Build first Python REST API test

Let's begin by writing a simple test that validates the response status code. All we need to do to get started is create a new Python file (we can create a new project in any IDE as well). What's happening here? We have imported the requests library to perform a REST API call.

How do I make a Postman script? ›

Scripting before your request runs
  1. Select Collections in the sidebar.
  2. Open the request, then select the Pre-request Script tab.
  3. Enter the JavaScript you need to process before the request runs, then select Save.
  4. Select Send to send the request. The code will execute before Postman sends the request to the API.
Jul 29, 2022

Is Postman a REST API? ›

Postman began as a REST client and has evolved into today's comprehensive Postman API Platform.

What is pre request script in Postman? ›

You can use pre-request scripts in Postman to execute JavaScript before a request runs. By including code in the Pre-request Script tab for a request, collection, or folder, you can carry out pre-processing such as setting variable values, parameters, headers, and body data.

What is Postman application used for? ›

Postman is an application used for API testing. It is an HTTP client that tests HTTP requests, utilizing a graphical user interface, through which we obtain different types of responses that need to be subsequently validated.

Videos

1. POSTMAN BEGINNER TUTORIAL 3 💡 How to create First API Request
(Automation Step by Step)
2. Automating Flickr API using python and Postman
(Pradeep Adithyan M)
3. API Testing using Python - Write First Test Case - Get Request(For Full Course - Check Description )
(Testing World)
4. Python Requests Tutorial: Request Web Pages, Download Images, POST Data, Read JSON, and More
(Corey Schafer)
5. API Dev Workflow with FastAPI and Postman
(Postman)
6. Postman Beginner's Course - API Testing
(freeCodeCamp.org)

You might also like

Latest Posts

Article information

Author: Dr. Pierre Goyette

Last Updated: 09/16/2022

Views: 6162

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.