0% found this document useful (0 votes)
124 views

Api Programming Fundamentals

Uploaded by

Liviu Melioth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views

Api Programming Fundamentals

Uploaded by

Liviu Melioth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

API and Programmability Fundamentals

Black Belt Partner Academy Security Powered by Fire Jumper

Developer Advocate
Intro to Coding and APIs

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
The Human Interaction Challenge

Software
displays results
in User Interface
(UI)

User asks for data or


takes action by
interacting with UI

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
“It’s a way for two pieces of software
to talk to each other”

Application Programming Interface (API)

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
The Value-Proposition for APIs

>>> do(“repetitious work…”) request


Done.

response OK!

✓ Request actions be performed


✓ Get information
✓ Store information

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
The Value-Proposition for Programmability
Coding is the process of writing down instructions, in a language a
computer can understand, to complete a specific task.
Q: What task?
A: Your task.

for switch in my_network:


for interface in switch:
if interface.is_down() and interface.last_change() > thirty_days:
interface.shutdown()
interface.set_description("Interface disabled per Policy")

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
What Changed?
API & Language Maturity $ pip install requests
Collecting requests
✓ RESTful APIs Using cached
<-- output omitted for brevity -->
✓ Expressive Modern Languages
$ python
>>> import requests
Online Communities >>> requests.get("https://api.github.com")
✓ Open Source <Response [200]>

✓ Social Code Sharing (GitHub)

✓ Public Package Repositories

You can get powerful things done with relatively small amounts of code!

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Why Python?
• Domain Applicability
Established online DevOps Community

• Power and Flexibility


Create & Work With: Shell Scripts, Back-end Web APIs, Databases, Machine Learning, …

• Platform Flexibility
Run Your Code: Laptop, Server, VM, Container, Cloud, Cisco IOS Device

• We Like It!
We have: Laptop Stickers, T-Shirts, Social Profiles, and Emotional Connections to Our Code

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
A Brief Introduction to Git

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
The Need for Version Control
How do I make incremental changes and share my work with others?

How do I go back to the version of this file from (yesterday, last week, last
year, ...)?

What changed between version X and version Y of a file?

People have been making changes to the same file (or set of files)... How do I
reconcile and merge all these changes?

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Git vs. GitHub

Git

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Basic Git Terminology
• Repository (Repo) - A vault for storing version controlled files
• Working Directory – The visible directory and its contents
• Versioned Files – Files you have asked Git to track
• Un-Versioned Files – Files in your working directory not tracked by Git
• Commit – Snapshot in time (of your version controlled files)
• Branches – A safe place for you to work

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
A Peak Under the Hood
• Commits contain Trees
• Trees contain links to Files
• Git stores full copies of all Changed
Files

Image Source: http://git-scm.com

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
What All New Git
Users Do

Image Source: xkcd.com

© 2019
2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Useful Git Commands

Setup Tell git who you are git config --global user.name “your name”
one-time setup git config --global user.email [email protected]

Clone Clone (“download”) a git repository git clone url


Status Check the Status of your local repository git status
Checkout Create and Checkout a local Branch git checkout –b new-branch-name
A Branch Creates a “safe place” for your changes

Add Add a file to your next commit. git add filename


Commit Commit your changes. git commit –m “Your commit message.”
Checkout Checks-out a file from the last commit. git checkout filename
A File Reverts any changes you have made, and restores the last
committed version of a file.

Learn More: git --help and man git

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
DevNet Sample-Code Workflow
git checkout

Sample Sample
git clone Code Code
(master) (mycode)

Step Action Git Command git commit Edit


1. Clone the Remote Repository git clone url

2. Create and Checkout a Local Branch git checkout –b new-branch-name def f(x): def f(x):
... ...
3. Incrementally Commit Changes git add filename
git commit -m “Commit message”
...
git add ...

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Intro to Python | Part 1

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python Scripts
✓ Text Files (UTF-8)
✓ May contain Unicode
Some editors / terminals don’t
support Unicode
✓ Use any Text Editor
Using a Python-aware editor will
make your life better
✓ No Need to Compile Them

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Using a Python Interpreter

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Know Thy Interpreter
What interpreter are you using? What version is it?
❑ python $ python -V
❑ python2
❑ python3
❑ python3.5 Where is it?
❑ python3.6 $ where command
❑ other

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
What is a Virtual Environment?
$ python3 -m venv venv
➢ Directory Structure $
$ tree -L 1 venv/
➢ Usually associated with a Project venv/
├── bin
➢ An isolated environment for ├── include
├── lib
installing and working with └── pyvenv.cfg
Python Packages $
$ source venv/bin/activate
(venv) $

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Activating a Python Virtual Environment
source environment-name/bin/activate

✓ The activation script will modify your prompt.


✓ Inside a virtual environment your interpreter will always be `python`.

$ source venv/bin/activate
(venv) $
(venv) $
(venv) $ deactivate
$
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
PIP Installs Packages
• Included with Python v3+ (venv) $ pip install requests
Collecting requests
Coupled with a Python installation;
Downloading
may be called pip3 outside a venv <-- output omitted for brevity -->
Installing collected packages: idna, certifi, chardet, urllib3,
• Uses the open PyPI Repository requests
Python Package Index Successfully installed certifi-2018.4.16 chardet-3.0.4 idna-2.6
requests-2.18.4 urllib3-1.22
• Installs packages and their (venv) $
dependencies
• You can post your packages to PyPI!

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Using your Python Interpreter

How to… Command

Access the Python Interactive Shell $ python

Running a Python script $ python script.py

Running a script in ‘Interactive’ mode $ python -i script.py


Execute the script and then remain in the Interactive Shell

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python’s Interactive Shell
Accepts all valid Python statements
Use It To:
To Exit:
✓ Play with Python syntax Ctrl + D or exit()
✓ Incrementally write Code
✓ Play with APIs and Data
(venv) $ python
Python 3.6.5 (default, Apr 2 2018, 15:31:03)[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linuxType "help", "copyright", "credits" or
"license" for more information.
>>>

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Basic Python Syntax

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Basic Data Types
Python Values >>> type(3)
type() (examples) <class ‘int’>

int -128, 0, 42 >>> type(1.4)


<class ‘float’>
float -1.12, 0, 3.14159
>>> type(True)
bool True, False <class ’bool’>

str “Hello 😎” >>> type("Hello")


Can use ‘’, “”, and “””””” <class ’str’>

bytes b”Hello \xf0\x9f\x98\x8e” >>> type(b"Hello")


<class ‘bytes’>

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Numerical Operators
Math Operations >>> 5 + 2
7
Addition: + >>> 9 * 12
108
Subtraction: - >>> 13 / 4
Multiplication: * 3.25
>>> 13 // 4
Division: / 3
>>> 13 % 4
Floor Division: // 1
Modulo: % >>> 2 ** 10
1024
Power: **

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Variables
Names >>> b = 7
>>> c = 3
• Cannot start with a number [0-9] >>> a = b + c
• Cannot conflict with a language keyword >>> a
10
• Can contain: [A-Za-z0-9_-]
• Recommendations for naming (variables, >>> string_one = "Foo"
classes, functions, etc.) can be found in PEP8 >>> string_two = "Bar"
>>> new_string = string_one + string_two
Created with the = assignment operator >>> new_string
'FooBar'
Can see list of variables in the current
scope with dir()

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
In Python, Everything is an Object!
Use . (dot) syntax to access “things” >>> a = 57
>>> a.bit_length()
inside an object. 6
>>> "WhO wRoTe THIs?".lower()
'who wrote this?'

Terminology
When contained inside an object, we call…
Variable → Attribute
Function → Method

Check an object’s type with type(object)


Look inside an object with dir(object)
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Working with Strings
String Operations >>> "One" + "Two"
'OneTwo'
Concatenation: +
>>> "Abc" * 3
Multiplication: * 'AbcAbcAbc'

>>> "Hi, my name is {}!".format("Chris")


Some Useful String Methods 'Hi, my name is Chris!'

Composition: “{}”.format() >>> "a b c".split(" ")


['a’, 'b’, 'c']
Splitting: “”.split()
Joining: “”.join() >>> ",".join(['a’, 'b’, 'c'])
'a,b,c'

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Basic I/O
Get Input with input() Display Output with print()
• Pass it a prompt string • Can pass multiple values
• It will return the user’s input as a string • It will concatenate those values with
• You can convert the returned string to the data separators in between (default = spaces)
type you need int(), float(), etc. • It will add (by default) a newline (‘\n’) to the
end

>>> print(‘a’, ‘b’, ‘c’)


abc

>>> i = input(“Enter a Number: ”)


Enter a Number: 1
>>> int(i)
1

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Conditionals
Syntax: Comparison Operators:
if expression1: Less than <
statements…
elif expression2: Greater than >
statements… Less than or equal to <=
else:
statements… Greater than or equal to >=
Equal ==
✓ Indentation is important!
Not Equal !=
✓ 4 spaces indent recommended Contains element in

✓ You can nest if statements Combine expressions with: and, or


Negate with: not

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Conditionals | Examples
>>> b = 5 >>> words = "Foo Bar"
>>> if b < 0: >>> if "Bar" in words:
... print("b is less than zero") ... print("words contains 'Bar'")
... elif b == 0: ... elif "Foo” in words:
... print("b is exactly zero") ... print("words contains 'Foo'")
... elif b > 0: ...
... print("b is greater than zero") words contains 'Bar'
... else:
... print("b is something else")
...
b is greater than zero

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Functions | Don’t Repeat Yourself
Modularize your code >>> def add(num1, num2):
... result = num1 + num2
• Defining your own Functions ... return result
• (optionally) Receive arguments ...
>>>
• (optionally) Return a value
>>> add(3, 5)
8
Syntax:
def function_name(arg_names):
>>> def say_hello():
statements…
... print("Hello!")
return value >>>
... >>> say_hello()
Hello!
function_name(arg_values)

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Hands-on Exercise

© 2019
2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Hands-on Exercise Estimated Time: 15 minutes

Intro to Python – Part 1


Objectives Things to Consider
Practice what we have learned: • There are multiple ways you could complete these
• Inspecting Variable Types items – any functional way works!

• Writing Conditionals (if-statements) • Use the interactive shell if needed to test out some
syntax.
• Writing Functions
• Calling a Function

Exercise

1. Open intro-python/part1/hands_on_exercise.py in your editor.


2. Complete each of the TODO tasks. Solution
3. Run the script in your Terminal.
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Intro to Python | Part 2

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python Collections & Loops

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Data Structures / Collection Data Types

Name Notes Example


type()

list • Ordered list of items [‘a’, 1, 18.2]


• Items can be different data types
• Can contain duplicate items
• Mutable (can be changed after created)
tuple • Just like a list; except: (‘a’, 1, 18.2)
• Immutable (cannot be changed)
dictionary • Unordered key-value pairs {“apples”: 5,
dict • Keys are unique; must be immutable “pears”: 2,
• Keys don’t have to be the same data type “oranges”: 9}
• Values may be any data type
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Working with Collections

Name Creating Accessing Updating


type() Indexing
list l = [‘a’, 1, 18.2] >>> l[2] >>> l[2] = 20.4
18.2 >>> l
[‘a’, 1, 20.4]

tuple t = (‘a’, 1, 18.2) >>> t[0] You cannot update tuples after they have been created.
‘a’

dict d = {“apples”: 5, >>> d[“pears”] >>> d[“pears”] = 6


“pears”: 2, 2 >>> d
“oranges”: 9} {“apples”: 5, “pears”: 6, “oranges”: 9}

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Dictionary Methods
Some useful dictionary methods: >>> d = {"a": 1, "b": 2, "c": 3}

>>> d.items()
{}.items() dict_items([('a’,1), ('b’,2), ('c',3)])

{}.keys() >>> d.keys()


dict_keys(['a’, 'b’, 'c’])
{}.values()
>>> d.values()
dict_values([1, 2, 3])

There are many more! 😎

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Other “Batteries Included” Collections

Collection Description
namedtuple() factory function for creating tuple subclasses with named fields

deque list-like container with fast appends and pops on either end
Learn More @
ChainMap dict-like class for creating a single view of multiple mappings
docs.python.org
Counter dict subclass for counting hashable objects
OrderedDict dict subclass that remembers the order entries were added
defaultdict dict subclass that calls a factory function to supply missing values

UserDict wrapper around dictionary objects for easier dict subclassing

UserList wrapper around list objects for easier list subclassing


UserString wrapper around string objects for easier string subclassing

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
OrderedDict Collection
>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od["apples"] = 5
>>> od["pears"] = 2
>>> od["oranges"] = 9
>>>
>>> od["pears"]
2
>>> od["bananas"] = 12
>>> od
OrderedDict([('apples',5), ('pears',2), ('oranges',9), ('bananas',12)])

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Loops
Iterative Loops Conditional Loops
for individual_item in iterator: while logical_expression:
statements… statements…

>>> names = ["chris", "iftach", "jay"] >>> i = 0


>>> for name in names: >>> while i < 5:
... print(name) ... print(i)
... ... i += 1
...
chris
0
iftach 1
jay 2
3
4

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Unpacking
Q: What if you wanted to break out >>> a, b, c = [1, 2, 3]
>>> a
a collection to separate variables? 1
>>> b
2
>>> c
A: Unpack them! 3

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Iterating through a Dictionary
• Use the dictionary .items() method, Method returns
which returns a “list of tuples” dictionary items as a list
• Unpack each tuple into variable names of of (key, value) tuples,
your choosing to use within your block of which the for loop will
statements iteratively unpack into
your variable names.
>>> for fruit, quantity in fruit.items():
... print("You have {} {}.".format(quantity, fruit))
...
You have 5 apples.
You have 2 pears.
You have 9 oranges.

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python Script Structure
and Execution

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Importing and Using Packages & Modules
Import “other people’s” code into >>> import requests
>>> requests.get('https://google.com')
your script. <Response [200]>

Syntax:
import module >>> response = requests.get('https://google.com')
>>> response.status_code
from module import thing 200

Tons of Packages:
Python Standard Library
Python Package Index
GitHub

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Variable Scope
#!/usr/bin/env python
Open in Your Editor: """Demonstrate module vs. locally scoped variables."""

# Create a module variable


intro-python/part2/variable_scope.py module_variable = "I am a module variable."

# Define a function that expects to receive a value for an argument variable


def my_function(argument_variable):
"""Showing how module, argument, and local variables are used."""
# Create a local variable
local_variable="I am a local variable."

Code Review: print(module_variable, "...and I can be accessed inside a function.")


print(argument_variable, "...and I can be passed to a function.")
print(local_variable, "...and I can ONLY be accessed inside a function.")
• Module-scoped “Global” Variables
# Call the function; supplying the value for the argument variable

• Argument Variables
my_function(argument_variable="I am a argument variable.")

# Let's try accessing that local variable here at module scope


• Local Variables print("\nTrying to access local_variable outside of its function...")
try:
print(local_variable)
except NameError as error:
print(error)

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python Script Structure and Execution
#!/usr/bin/env python

Open in Your Editor: # """Module docstring."""

# Imports
import os
intro-python/part3/structure.py import sys

# Module Constants
START_MESSAGE = "CLI Inspection Script"

# Module "Global" Variables


location = os.path.abspath(__file__)

Code Review: # Module Functions and Classes


def main(*args):
""" My main script function.
• Structure Displays the full patch to this script, and a list of the arguments passed
to the script.
"""
• Flow print(START_MESSAGE)
print("Script Location:", location)
print("Arguments Passed:", args)

• Execution # Check to see if this file is the "__main__" script being executed
if __name__ == '__main__’:
_, *script_args = sys.argv
main(*script_args)

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Debugging Basics
• Add print() statements
Comment and uncomment them to “enable and disable your debugging”
• Understand how to read a Python Stake Trace
1. Last Line First
2. Top to Bottom
3. Stop when you reach someone else’s code
• Run a script and then stay in the Python Interactive Shell
Use the python –i option

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Reading a Python Stack Trace
fortune_cookie.py main() create_fortune_cookie_message()
$ python intro-python/part2/fortune_cookie.py
Get your fortune cookie!
How many lucky numbers would you like? 5
Traceback (most recent call last):
File "intro-python/part2/fortune_cookie.py", line 56, in <module>
main()
File "intro-python/part2/fortune_cookie.py", line 50, in main
fortune_cookie_message = create_fortune_cookie_message(qty_lucky_numbers)
File "intro-python/part2/fortune_cookie.py", line 38, in create_fortune_cookie_message
raise NotImplementedError()
NotImplementedError

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Hands-on Exercise

© 2019
2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Hands-on Exercise Estimated Time: 15 minutes

Intro to Python – Part 2


Objectives Things to Consider
Practice what we have learned: • There are multiple ways you could complete these
• Understanding Script Execution & Flow items – any functional way works!

• Variable Scope • You only need to do work inside the


create_fortune_cookie_message() function.
• Practice Basic Debugging
• Feel free to add debug print() statements wherever
you like.

Exercise

1. Open intro-python/part2/fortune_cookie.py in your editor.


2. Complete the TODO task. Solution
3. Run the script in your Terminal.
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Parsing JSON with Python

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
What is JSON?
• Standardized format for passing data as text.
• JavaScript Object Notation
• Looks strikingly similar to Python’s syntax for dictionaries, lists, strings and
number types!
• …BUT… JSON is just text!

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
JSON Syntax vs. Python Syntax
{ {
"ietf-interfaces:interface": { 'ietf-interfaces:interface': {
"name": "GigabitEthernet2", 'name’: 'GigabitEthernet2’,
"description": "Wide Area Network", 'description’: 'Wide Area Network’,
"enabled": true, 'enabled’: True,
"ietf-ip:ipv4": { 'ietf-ip:ipv4': {
"address": [ 'address': [
{ {
"ip":"172.16.0.2", 'ip':'172.16.0.2’,
"netmask":"255.255.255.0" 'netmask':'255.255.255.0’,
} },
] ],
} },
} },
} }
JSON Python

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Reading-from and Writing-to Files
Use the python open() function. >>> file = open("demo.txt")
>>> contents = file.read()
>>> print(contents)
open(file_path, mode=‘r’) It's easy to work with files in Python!

>>> file.close()

File Methods:
.read() >>> with open("demo.txt") as file:
... print(file.read())
.write() ...
It's easy to work with files in Python!
.close()

Use the with statement if you don’t want to have to remember to close the file after you are done working with a file.
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Parsing JSON
Parsing: Converting the text-based JSON data to >>> string = '{"pets": ["cat", "dog"]}’
native Python data types - things you can work >>> type(string)
with! <class'str'>

Python provides a native JSON parser for you! >>> import json
>>> data = json.loads(string)

import json >>> type(data)


<class'dict'>
data = json.load(file)
data = json.loads(string) >>> data["pets"][1]
string = json.dump(file) 'dog'

string = json.dumps(data)

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Nested Data

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Accessing Nested Data
Indexing into Nested Data json_data = {
'ietf-interfaces:interface': {
1. Start with the outermost data structure. 'name’: 'GigabitEthernet2’,
'description’: 'Wide Area Network’,
2. “Extract” from it what we want.
'enabled’: True,
3. Repeat. 'ietf-ip:ipv4': {
'address': [
➢ Play with data in the Python Interactive Shell {
'ip':'172.16.0.2’,
➢ Takes practice. 'netmask':'255.255.255.0’,
},
How would you access the “ip” address ],
},
in this example? },
}

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Solution

>>> json_data["ietf-interfaces:interface"]["ietf-ip:ipv4"]["address"][0]["ip"]
'172.16.0.2'

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Hands-on Exercise

© 2019
2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Hands-on Exercise Estimated Time: 15 minutes

Parsing JSON with Python


Objectives Things to Consider
Practice what we have learned: • There are multiple ways you could complete these
• Parsing JSON with the json module items – any functional way works!

• Indexing Nested Data • Remember your basic debugging tools.


• Iterating through a Dictionary • You will need to index to the data structure you
want to iterate.

Exercise

1. Open intro-python/parsing-json/nested_data.py in your editor.


2. Complete each of the TODO tasks. Solution
3. Run the script in your Terminal.
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Wrap Up

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
What you learned in this module…
• How to clone a git repo, create branches, and make commits.
• Core Python syntax, operators, conditionals, and functions.
• Python container data types and syntax for Python’s loops.
• Python script structure, execution, and variable scoping and passing.
• How to parse JSON (aka. convert to native Python data types) and extract
and reference it’s data.

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
…where to go to continue learning:
DevNet (always!) Python
https://developer.cisco.com edx.org Python Courses
coursera.com Python Courses
Git
codecademy.com Learn Python
git-scm.com Tutorials
Need a challenge?
GitHub
GitHub Guides

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential

You might also like