Api Programming Fundamentals
Api Programming Fundamentals
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)
© 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”
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
The Value-Proposition for APIs
response OK!
© 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.
© 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]>
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
• 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, ...)?
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
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
What All New Git
Users Do
© 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]
© 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)
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
$ 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
© 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’>
© 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
© 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
© 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
© 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
• Writing Conditionals (if-statements) • Use the interactive shell if needed to test out some
syntax.
• Writing Functions
• Calling a Function
Exercise
© 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
tuple t = (‘a’, 1, 18.2) >>> t[0] You cannot update tuples after they have been created.
‘a’
© 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)])
© 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
© 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…
© 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."""
• Argument Variables
my_function(argument_variable="I am a argument variable.")
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python Script Structure and Execution
#!/usr/bin/env python
# Imports
import os
intro-python/part3/structure.py import sys
# Module Constants
START_MESSAGE = "CLI Inspection Script"
• 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
Exercise
© 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)
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
Exercise
© 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