|
| 1 | +# Parsing JSON using Python |
| 2 | + |
| 3 | +In this Learning Lab, you learn the basics of parsing JSON content using Python. The example runs a query on the [ACI Always-On Sandbox](https://devnetsandbox.cisco.com/RM/Diagram/Index/5a229a7c-95d5-4cfd-a651-5ee9bc1b30e2?diagramType=Topology "ACI Always-On Sandbox") to request data for available configuration on the fabric. You will then parse this returned data and print it to the screen for human readability. |
| 4 | + |
| 5 | +To learn more about ACI and its API, you can review the DevNet [Learning Lab track for ACI programmability](https://developer.cisco.com/learning/tracks/aci-programmability), which teaches a variety of different ways to interact with ACI programmatically. ACI is used as a basis for these labs as the managed object model within ACI allows us to query the same object or class within the fabric and return both XML and JSON data structures, simply based on changing the file-type within the REST URL. |
| 6 | + |
| 7 | +## Objectives |
| 8 | + |
| 9 | +When you have completed this Learning Lab, you will be able to: |
| 10 | + |
| 11 | +* Understand the basics of reading and parsing HTTP content using Python. |
| 12 | +* Learn how to use Python to extract only the JSON data you want using the JSON library. |
| 13 | + |
| 14 | +## Prerequisites |
| 15 | + |
| 16 | +* Complete the [Coding Fundamentals](https://developer.cisco.com/learning/modules/programming-fundamentals) and [REST API Fundamentals](https://developer.cisco.com/learning/modules/rest-api-fundamentals) Learning Lab modules if you are unfamiliar with Python and retrieving results from a RESTful service and the [Parsing XML using Python Lab](lab/coding-201-parsing-xml/step/1 "Parsing XML using Python Lab") for a similar approach to retrieving data using XML. |
| 17 | + |
| 18 | +* You should also have a basic familiarity with JSON. Otherwise, consider visiting the [W3Schools JSON Tutorial](https://www.w3schools.com/js/js_json_intro.asp "W3Schools JSON Tutorial") to get a firm base to build upon. |
| 19 | + |
| 20 | +* For this lab, use Python 3.4+. To verify your version, enter the following command in a terminal: |
| 21 | + |
| 22 | +``` |
| 23 | + python --version |
| 24 | +``` |
| 25 | + |
| 26 | +If you are on a DevNet Zone station, the correct version of Python should already be installed. |
| 27 | + |
| 28 | +# Step 1: Make an HTTP REST call with Python |
| 29 | + |
| 30 | +> **Note**: This lab leverages the DevNet Always-On ACI Sandbox, however you can substitute this with a local APIC if you have one available. The sets of sample code contained within this lab will not perform any write or configuration actions against the fabric; they will only request currently configured data. |
| 31 | +
|
| 32 | +To get started, this walk-through shows creating a simple Python script that sends an HTTP request to the ACI sandbox. |
| 33 | + |
| 34 | +1. Open a text editor and create a file named `get-tenant-json.py`. |
| 35 | +3. Add the following lines to `get-tenant-json.py`: |
| 36 | + |
| 37 | + ```python |
| 38 | + import requests |
| 39 | + # We need to import the JSON library just to handle our request to the APIC for login |
| 40 | + import json |
| 41 | + # We need to log in to the APIC and gather a token, before we can access any data |
| 42 | +# Let's construct a request with a body |
| 43 | + |
| 44 | +# We'll need to disable certificate warnings |
| 45 | +requests.packages.urllib3.disable_warnings() |
| 46 | + |
| 47 | +# We need to have a body of data consisting of a username and password to gather a cookie from APIC |
| 48 | +encoded_body = json.dumps({ |
| 49 | + "aaaUser": { |
| 50 | + "attributes": { |
| 51 | + "name": "admin", |
| 52 | + "pwd": "ciscopsdt" |
| 53 | + } |
| 54 | + } |
| 55 | +}) |
| 56 | + |
| 57 | +# Now lets make the request and store the data |
| 58 | +resp = requests.post("https://sandboxapicdc.cisco.com/api/aaaLogin.json", data=encoded_body, verify=False) |
| 59 | + |
| 60 | +# This stores the received APIC-cookie from the login as a value to be used in subsequent REST calls |
| 61 | +header = {"Cookie": "APIC-cookie=" + resp.cookies["APIC-cookie"]} |
| 62 | + |
| 63 | +# Now we make a call towards the tenant class on the ACI fabric with the proper header value set. |
| 64 | +# We leverage the .xml ending to receive the data back as XML. We're adding health and faults to the printout to ensure that we get levels of data back from the APIC |
| 65 | +tenants = requests.get("https://sandboxapicdc.cisco.com/api/node/class/fvTenant.json?rsp-subtree-include=health,faults", headers=header, verify=False) |
| 66 | + |
| 67 | +# Requests stores the text of the response in the .text attribute. Lets print it to see raw JSON |
| 68 | +print(tenants.text) |
| 69 | +``` |
| 70 | +There is a lot of manipulation going on with the top part of this script, but most of it deals with the methods needed to authenticate towards the ACI fabric, needing a username and password to authenticate, receive the response from the fabric and gather a token, then send this token in a subsequent call to the fabric to pull the ACI tenant information out in JSON format. However, this snippet: |
| 71 | + |
| 72 | + - imported the `request` library to easily interact with the ACI fabric's REST APIs |
| 73 | + - constructed a call to authenticate against the APIC and store the authentication token as a cookie to be used later |
| 74 | + - created a request to ask for all configured tenants in the fabric using the stored authentication cookie |
| 75 | + - accessed the response from the query and printed the raw JSON output to the console/terminal <br> |
| 76 | + |
| 77 | +4. Save the `get-tenant-json.py` file. To download or review the current code, you can get it from GitHub [here](https://github.com/CiscoDevNet/coding-skills-sample-code/blob/master/coding202-parsing-json/get-tenant-json-1.py). |
| 78 | + |
| 79 | +5. Open a command prompt.<br> |
| 80 | + <br> |
| 81 | + For Windows, enter: |
| 82 | + |
| 83 | + ``` |
| 84 | + cd %USERPROFILE%\Desktop |
| 85 | + ``` |
| 86 | + |
| 87 | + For OS X, enter: |
| 88 | + |
| 89 | + ``` |
| 90 | + cd ~/Desktop |
| 91 | + ``` |
| 92 | + |
| 93 | +6. In the command prompt window, enter: |
| 94 | + |
| 95 | + ``` |
| 96 | + python get-tenant-json.py |
| 97 | + ``` |
| 98 | + |
| 99 | +7. The command line/terminal displays the JSON data retrieved by the script. |
| 100 | + |
| 101 | + |
| 102 | + |
| 103 | +-------------------------------------------------------------------------------- |
| 104 | + |
| 105 | +This presentation of the JSON data isn't very useful. Next, clean up the presentation to get a better view of the structure and content of the data. |
| 106 | + |
| 107 | +**Next step:** Proceed to Step 2: Use the JSON Python library. |
0 commit comments