Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
122 views

2 Python Programming

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)
122 views

2 Python Programming

Uploaded by

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

Intro to Coding and APIs

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Intro to Coding and APIs

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
https://developer.cisco.com/learning/devnet-
express/dnav4-track

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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Why Python ?

• PowerFull
• Flexible
• Easy To learn
• Tons of libraries
already exist

© 2017 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python as a standard
LEARNING SHARE

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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Setup & Activate your Python Virtual Environment
• LINUX Open bash terminal at the “root of the repository”
• Windows open a CMD console and CD to your working directory
• Create and activate a Python virtual environment

# MacOS or Linux # Windows (bash)


python3.6 -m venv venv python -m venv venv
source venv/bin/activate venv\Scripts\activate

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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
$
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Activating a Python Virtual Environment WINDOWS
environment-name/bin/activate

$ venv/bin/activate
(venv) $
(venv) $
(venv) $ deactivate
$

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python interpreter

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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.
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Open Your Python console – let’s work within it
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47)
[MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Basic Python Syntax

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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’>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Numerical Operators
Math Operations >>> 5 + 2
7
Addition: + >>> 9 * 12

Subtraction: - 108
>>> 13 / 4
Multiplication: * 3.25
>>> 13 // 4
Division: / 3
Floor Division: // >>> 13 % 4
1
Modulo: % >>> 2 ** 10
Power: ** 1024

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables – some rules
Names >>> variable =

• Cannot start with a number [0-9]


• Cannot conflict with a language keyword
• Can contain: [A-Za-z0-9_-]
• Recommendations for naming (variables,
classes, functions, etc.) can be found in
PEP8

Created with the = assignment


operator

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables ( int )
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,
classes, functions, etc.) can be found in
PEP8

Created with the = assignment


operator
Can see list of variables in the
current scope with dir()

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables ( strings )
Use quotes ! >>>
>>> firstname ='Patrick '
Created with the = assignment >>>
>>> lastname ="cardot"
operator >>>
>>> name = firstname + lastname
>>>
Can see list of variables in the >>> name

current scope with dir()


'patrickcardot’
>>>
>>> name = firstname + " " + lastname
>>> name
'patrick cardot'
>>>
>>> age = 25
>>>
>>> name = firstname + " " + lastname + " " + age
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>>
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Operation on variables
Operation on different variable types >>> age = 25
>>> name = firstname + " " + lastname + " " + age
is not allowed Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Concatenate string + integer TypeError: can only concatenate str (not "int") to str
>>>
Numerical operation with string + >>>
integer >>>
>>> name = firstname + " " + lastname + " " + str(age)
>>>
>>> name
Can see list of variables in the 'patrick cardot 25'
current scope with dir() >>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables are objects
Let’s see the list of “possible action”( >>>
>>> dir(name)
methods ) in the current scope with ['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
dir() '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
dir ( variable_name ) '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
In Python, Everything is an Object!
Use . (dot) syntax to access >>> a = 57
>>> a.bit_length()
“things” 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)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables are objects
name.split ('') >>>
>>> name
'patrick cardot 25'
>>> test=name.split("car")
>>> test
['patrick ', 'dot 25']
>>>
>>>
>>> test=name.split(" ")
>>>
>>> test
['patrick', 'cardot', '25']
>>>
>>> test=name.split("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: empty separator
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables are objects
name.split () >>>
>>> test=name.split()
>>> test
['patrick', 'cardot', '25']
>>>
>>> type(test)
<class 'list'>
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables are objects
A string is a list of chars >>>
>>> test=name.split()
>>> test
['patrick', 'cardot', '25']
>>>
>>> type(test)
<class 'list'>
>>>
>>>
>>> test[0]
'patrick'
>>>
>>> test[0][0]
'p'
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables are objects
paragraph="AMP for Endpoint
Copy the following and paste it in the File "<stdin>", line 1
paragraph="AMP for Endpoint
python console. ^
SyntaxError: EOL while scanning string literal
>>> Reduce the attack surface using multifaceted prevention techniques and posture
assessments.
File "<stdin>", line 1
Reduce the attack surface using multifaceted prevention techniques and posture
paragraph=‘AMP for Endpoint assessments.
^
SyntaxError: invalid syntax
Reduce the attack surface using multifaceted >>> Reduce incident response time by up to 85 percent to fully expose, contain, and
resolve threats and vulnerabilities.
prevention techniques and posture assessments. File "<stdin>", line 1
Reduce incident response time by up to 85 percent to fully expose, contain, and
resolve threats and vulnerabilities.
Reduce incident response time by up to 85 ^
SyntaxError: invalid syntax
percent to fully expose, contain, and resolve >>> Boost SecOps effectiveness by up to 86 percent by eliminating complexity and
threats and vulnerabilities. enhancing staff productivity.
File "<stdin>", line 1
Boost SecOps effectiveness by up to 86 percent by eliminating complexity and
Boost SecOps effectiveness by up to 86 percent enhancing staff productivity.
^
by eliminating complexity and enhancing staff SyntaxError: invalid syntax
>>>
productivity."
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Variables are objects
>>>
Copy the following and paste it in the >>>
python console. >>> paragraph='''AMP for Endpoint
... Reduce the attack surface using multifaceted prevention
techniques and posture assessments.
... Reduce incident response time by up to 85 percent to fully
expose, contain, and resolve threats and vulnerabilities.
paragraph='''AMP for Endpoint ... Boost SecOps effectiveness by up to 86 percent by eliminating
complexity and enhancing staff productivity.'''
>>>
Reduce the attack surface using multifaceted >>>
prevention techniques and posture assessments. >>> paragraph
'AMP for Endpoint\nReduce the attack surface using multifaceted
Reduce incident response time by up to 85 prevention techniques and posture assessments.\nReduce incident
response time by up to 85 percent to fully expose, contain, and
percent to fully expose, contain, and resolve resolve threats and vulnerabilities.\nBoost SecOps effectiveness by
threats and vulnerabilities. up to 86 percent by eliminating complexity and enhancing staff
productivity.'
>>>
Boost SecOps effectiveness by up to 86 percent >>>
by eliminating complexity and enhancing staff
productivity. '''
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Split this paragraph in lines
Lines = paragraph.split("\n") >>>
>>> Lines=paragraph.split("\n")
>>> Lines
['AMP for Endpoint', 'Reduce the attack surface using
\n : new line multifaceted prevention techniques and posture assessments.',
'Reduce incident response time by up to 85 percent to fully
\r : carriage return
expose, contain, and resolve threats and vulnerabilities.', 'Boost
\t : tab SecOps effectiveness by up to 86 percent by eliminating
complexity and enhancing staff productivity.']
>>> type(Lines)
<class 'list'>
>>>
>>> Lines[1]
'Reduce the attack surface using multifaceted prevention
techniques and posture assessments.'
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
The For loop
line="" >>>
>>> >>>
For line in Lines: >>> line = ''
>>> for line in Lines: <enter>
... <tab>line
... <enter>

'AMP for Endpoint'


'Reduce the attack surface using multifaceted prevention
techniques and posture assessments.'
'Reduce incident response time by up to 85 percent to fully
expose, contain, and resolve threats and vulnerabilities.'
'Boost SecOps effectiveness by up to 86 percent by eliminating
complexity and enhancing staff productivity.'
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Working with Strings
String Operations >>> "One" + "Two"
'OneTwo'
Concatenation: +
Multiplication: * >>> "Abc" * 3
'AbcAbcAbc'

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


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

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


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

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


'a,b,c'

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Working with Strings
String Operations >>> variable1="Taylor"
>>> variable2="Rich"
Concatenation: + >>> text="My {} is {}".format(variable1,variable2)

Multiplication: * >>> text


'My Taylor is Rich'
>>>

Some Useful String Methods


Composition: "{} ".format()

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Working with Strings
String Operations >>> variable1="Taylor"
>>> variable2="Rich"
Concatenation: + >>> text=f"My {variable1} is {variable2}"

Multiplication: * >>> text


'My Taylor is Rich'
>>>

Some Useful String Methods


Composition:
f " {var1}…xxx…{var2}… "

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab Time

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Challenge ( 15 mins )
• variable = "apple, orange, strawberry-data"
• write a script called challenge-1.py which outputs the following
result:

word 1 = *APPLE*
word 2 = *ORANGE*
word 3 = *STRAWBERRY*

Remark : Have a look to the uppercase result and the stars *

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s move forward

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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
separators in between (default =
• You can convert the returned string to spaces)
the data type you need int(), float(), • It will add (by default) a newline (‘\n’)
etc. to the end

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


abc

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


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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Functions | Don’t Repeat Yourself
Modularize your code >>> def add(num1, num2):
... <tab>result = num1 + num2
• Defining your own Functions ... <tab>return result
• (optionally) Receive arguments ...
>>>
• (optionally) Return a value
>>> add(3, 5)

Syntax: 8

def function_name(arg_names):
statements… >>> def say_hello():
... print("Hello!")
return value >>>
... >>> say_hello()
function_name(arg_values) Hello!

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Functions | Pass variables
Use variables >>> def add(num1,num2):
... result = num1 + num2
... return result
...
>>> add(5,6)
11
>>>
>>>
>>> var1=9
>>> var2=45
>>> add(var1,var2)
54
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Functions | Pass variables – define default values
def add2(num1,num2=8): >>>
>>> def add2(num1,num2=8):
... result = num1 + num2
... return result
...
>>>
>>> add2(num1=3)
11
>>>
>>>
>>> add2(num1=3,num2=21)
24
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Functions | Pass variables – pass a dictionnary
dict_var={'num1':34,'num2':56} >>>
>>> dict_var={'num1':34,'num2':56}
add2(**dict_var) >>>
>>> add2(**dict_var)
90

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Importing and Using Packages & Modules
Try this
>>> >>>
>>>
>>> >>> i = random.randint(0, 100)
Traceback (most recent call last):
>>> i = random.randint(0, 100) File "<stdin>", line 1, in <module>
NameError: name 'random' is not defined
>>>
>>>
>>> >>>

And print the result

Random module is missing !

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Importing and Using Packages & Modules
Fix That !
>>> >>>
>>>
>>> >>>>>>
>>> import random
>>> i = random.randint(0, 100) >>>
>>> i = random.randint(0, 100)
>>>
>>>
>>> >>> print(str(i))
69
And print the result >>>
>>>
>>>

Random module is missing !

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Importing and Using Packages & Modules
Try this now and Fix That !
>>> >>>
>>> print(yellow("Hello World !",bold=True))
>>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
>>> print(yellow("Hello World !",bold=True)) NameError: name 'yellow' is not defined
>>>
>>>
>>>
>>> >>> import crayon
Traceback (most recent call last):
And print the result File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'crayon'
>>>

The crayons module is missing !


Try to import it !

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Importing and Using Packages & Modules
Let’s Fix That !
Let’s install the missing python module pip install crayons
Collecting crayons
Using cached
https://files.pythonhosted.org/packages/5b/0d/e3fad4ca
1de8e70e06444e7d777a5984261e1db98758b5be3e8296
c03fe9/crayons-0.4.0-py2.py3-none-any.whl
Collecting colorama (from crayons)
Using cached
https://files.pythonhosted.org/packages/44/98/5b86278f
bbf250d239ae0ecb724f8572af1c91f4a11edf4d36a206189
440/colorama-0.4.4-py2.py3-none-any.whl
Installing collected packages: colorama, crayons
Successfully installed colorama-0.4.4 crayons-0.4.0
You are using pip version 10.0.1, however version 20.3b1
is available.
You should consider upgrading via the 'python -m pip
install --upgrade pip' command.

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Importing and Using Packages & Modules
Let’s Fix That !
Import the crayons module >>> import crayons
>>>
>>> print(yellow("Hello World !",bold=true))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'yellow' is not defined
>>>
>>>
>>> from crayons import blue, green, white, red,
yellow,magenta, cyan
>>> print(yellow("Hello World !",bold=True))
Hello World !
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Importing and Using Packages & Modules
Import “other people’s” code
>>> import requests
into your script. >>> requests.get('https://google.com')
<Response [200]>
Syntax:
import module
>>> response = requests.get('https://google.com')
from module import thing
>>> response.status_code
200
Tons of Packages:
Python Standard Library
Python Package Index
GitHub

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab Time

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Challenge – 2 ( 15 mins )
• write a script called challenge-2.py which ask you to input either the following words :
green, red or cyan ( handle input case )
• If you enter anything else then script tells you that you are wrong and take you back to the
input step.
• If you enter green then the script must display :
• Ok green is GREEN

• If you enter red then the script must display :


• Ok red is red

• If you enter cyan then the script must display :


• Ok cyan is CYAN
Start your script by creating a list :

WordList = [‘green’,’red’,’cyan’]
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s move forward
Collections

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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
‘a’ created.

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


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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
List – print all items
Use the for loop variable = "apple, orange, strawberry"

word_list=variable.split(',')

print(word_list)

for word in word_list:


print(word)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
List – add an item to a list
VarList.append(new_item) variable = "apple, orange, strawberry"

word_list=variable.split(',')

print(word_list)

for word in word_list:


print(word)

New_var= " banana “


word_list.append(New_var)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
List – check if a list is empty

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
List – check that an item exist

Don't try to have access to item indexes greater than : list.count(List_of_item)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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! 😎

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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 (key, value) tuples,
of your choosing to use within your which the for loop will
block of statements iteratively unpack into
your variable names.
>>>fruit={'apple':5,'pears':2,'oranges':2}
>>> for fruit, quantity in fruit.items():
... print("You have {} {}.".format(quantity, fruit))
...
You have 5 apples.
You have 2 pears.
You have 9 oranges.

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Dictionary – add an item
VarDict["key"]="value" >>> payload={}
>>> payload.update({"name":"New_Host"})

or >>> payload.update({"ip_addrr":"192.168.10.12"})
>>> payload.update({"mask":"255.255.255.0"})

VarDict.update({"key":"value"})
>>> print(payload)
{'name': 'New_Host', 'ip_addrr': '192.168.10.12', 'mask':
'255.255.255.0'}
>>> print(payload['name'])
New_Host
>>>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Check if a dictionary is empty

• if test_dict:
• print "text_dict not empty"
• else:
• print " text_dict empty"

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Check if a key exist ?
if 'key1' in dict.keys():
print "Key exists"
else:
print "Key Doesn't exist"

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s move forward
files

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Reading-from and Writing-to Files
Use the python open() function. >>> file = open("demo.txt“,”r”)
>>> 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())
.close() ...
It's easy to work with files in Python!

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.
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Writing-to Files
Use the python open() function. paragraph='''some text
to write. '''
open(file_path, mode="w") file = open("demo.txt","w")
file.write(paragraph)
open(file_path, mode="a+") file.close()

File Methods:
with open("demo2.txt","w") as file:
.write() file.write(paragraph)

.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.
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
TIPS : locate your working directory

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
• LUNCH BREAK !
• UNTIL 13h15 Paris Time ?

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s move forward

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Script Structure
and Execution

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
#!/usr/bin/env python
"""Demonstrate module vs. locally scoped variables."""

Variable Scope # Create a global variable


module_variable = "I am a global variable."

Open in Your Editor: # Define a function that expects to receive a value for an argument variable
def my_function(argument_variable):
variable_scope.py """Showing how module, argument, and local variables are used."""
# Create a local variable
local_variable="I am a local variable."

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


print(argument_variable, "...and I can be passed to a function.")
Code Review: 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.")

• Local Variables # Let's try accessing that local variable here at module scope
print("\nTrying to access local_variable outside of its function...")
try:
print(local_variable)
except NameError as error:
print(error)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Script Structure
#!/usr/bin/env python
# """Module docstring."""

and Execution # Imports


import os
import sys

Open in Your Editor: # Module Constants


START_MESSAGE = "CLI Inspection Script"
structure.py
# Module "Global" Variables
location = os.path.abspath(__file__)

# Module Functions and Classes


Code Review: 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)
• Execution
print("Arguments Passed:", args)

# Check to see if this file is the "__main__" script being executed


if __name__ == '__main__’:
_, *script_args = sys.argv
main(*script_args)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Script Structure #!/usr/bin/env python
# """Module docstring."""

and Execution # Imports


import os
import sys

Indentation ! # Module Constants


START_MESSAGE = "CLI Inspection Script"

# Module "Global" Variables

4 x space ( default )
location = os.path.abspath(__file__)

# Module Functions and Classes


Or def main(*args):
""" My main script function.

Tab
Displays the full patch to this script, and a list of the arguments passed
to the script.
"""
print(START_MESSAGE)
print("Script Location:", location)
print("Arguments Passed:", args)

# Check to see if this file is the "__main__" script being executed


if __name__ == '__main__’:
_, *script_args = sys.argv
main(*script_args)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Script Structure and Execution
Add some comments in Your
#!/usr/bin/env python
'''
Here is how to comment
code several consecutives lines
'''

# Imports
import os
import sys

# Module Constants
START_MESSAGE = "CLI Inspection Script"

# Module "Global" Variables


location = os.path.abspath(__file__)

# Module Functions and Classes


def main(*args):
""" My main script function.

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Script Pass variable from the CLI
sys.argv
….

# Module Functions and Classes


def main(*args):
""" My main script function.

Displays the full patch to this script, and a list of the arguments
passed
to the script.
"""
print(START_MESSAGE)
print("Script Location:", location)
print("Arguments Passed:", args)
print(“First Arguments Passed:", args[0])

# Check to see if this file is the "__main__" script being executed


if __name__ == '__main__’:
_, *script_args = sys.argv
main(*script_args)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Try.. Except
The try block lets you test a try:
block of code for errors. f = open("demofile.txt")
f.write("Lorum Ipsum")
The except block lets you handle except:
the error. print("Something went wrong when writing to the file")
finally:

The finally block lets you execute f.close()

code, regardless of the result of


the try- and except blocks.

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Try Except : example

try:
# Get list of clients on network, filtering on timespan of last 14 days
clients = dashboard.networks.getNetworkClients(net['id'], timespan=60*60*24*14, perPage=1000, total_pages=
except meraki.APIError as e:
print(f'Meraki API error: {e}')
print(f'status code = {e.status}')
print(f'reason = {e.reason}')
print(f'error = {e.message}')

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Troubleshooting & debug

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
debug
If debug: from crayons import *

… debug = 1


def get_line():
currentfram=currentframe()
return currentfram.f_back.f_lineno


if debug:
print(cyan(get_line(),bold=True))
print(cyan( some_output_to_check ))

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Stop the code with sys_exit()
• sys.exit() ...
...
if ctr_action_response == 200:
print(green(f"OK GOOD !"))

print(yellow(ctr_action_response))
sys.exit()
user = get_user_details(webex_token)
...
...

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Common issue
• Indentation
• Missing column at the end of for… or if…
• Empty list item
• Empty dictionary items
• Type mismatch during operation
• Quotes :
• not valid : « », ` , “ , ” , ‘ ,
• Valid : " , '

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab Time

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Challenge – 4 ( 10 mins )
• Start from your challenge-1.py script and create a script named challenge-4.py
• Rewrite this new script by the respect of all rules and best practices previously explained

import modules
Create a main function that calls other functions
Create those functions
Create global variables
document your code
etc…

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Parsing JSON with Python

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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!

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
What is JSON?
• Standardized format for passing data as {
text. "ietf-interfaces:interface": {
"name": "GigabitEthernet2",
• JavaScript Object Notation "description": "Wide Area Network",
"enabled": true,
• JSON is just text! "ietf-ip:ipv4": {
"address": [
• Store data in a easy to access and {
organized object "ip":"172.16.0.2",
"netmask":"255.255.255.0"
}
]
}
}
}

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Nested Data

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Convert a Dictionary to JSON
import json
import json
json_dict ={
string = json.dump(file) "albumId": 1,
"id": 1,
string = json.dumps(data) "title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
}

print(type(json_dict))
<class 'dict'>

string = json.dumps(json_dict)

print(type(string))
<class 'str'>

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Convert JSON to a Dictionnary
import json >>> string = '{"pets": ["cat", "dog"]}’
>>> type(string)
Dict_data = json.load(file) <class'str'>

Dict_data = json.loads(string) >>> import json


>>> data = json.loads(string)

>>> type(data)
<class'dict'>

>>> data["pets"][1]
'dog'

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
What type is this ?
A STRING json_data = ''' {
'ietf-interfaces:interface': {
'name’: 'GigabitEthernet2’,
'description’: 'Wide Area Network’,
'enabled’: True,
'ietf-ip:ipv4': {
'address': [
{
'ip':'172.16.0.2’,
'netmask':'255.255.255.0’,
},
],
},
}
} '''

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
What type is this ?
A DICTIONNARY json_data = {
'ietf-interfaces:interface': {
'name’: 'GigabitEthernet2’,
'description’: 'Wide Area Network’,
'enabled’: True,
'ietf-ip:ipv4': {
'address': [
{
'ip':'172.16.0.2’,
'netmask':'255.255.255.0’,
},
],
},
}
}

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
What type is this ?
A List json_data =[ {
'ietf-interfaces:interface': {
'name’: 'GigabitEthernet2’,
'description’: 'Wide Area Network’,
'enabled’: True,
'ietf-ip:ipv4': {
'address': [
{
'ip':'172.16.0.2’,
'netmask':'255.255.255.0’,
},
],
},
}
}]

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
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",
"netmask":"255.255.255.0’ "
➢ Takes practice. }
]
How would you access the “ip” }
}
address in this example? }

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
JSON Path Finder

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
JSON data examples
( copy and paste into json path finder )
{ "ietf-interfaces:interface": { "name": "GigabitEthernet2",
"description": "Wide Area Network", "enabled": true, "ietf-ip:ipv4":
{ "address": [ { "ip":"172.16.0.2",
"netmask":"255.255.255.0" } ] } }}

https://jsonplaceholder.typicode.com/photos

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Solution

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

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Format the JSON output
Import requests
Import json

url = "https://jsonplaceholder.typicode.com/photos"

response = requests.get(url)
print(response)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Format the JSON output

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Format the JSON output
Import requests
Import json

url = "https://jsonplaceholder.typicode.com/photos"

response = requests.get(url)
print(json.dumps(response.json(),indent=4,
sort_keys=True,
separators=(',', ': '))
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Format the JSON output

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab Time

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Try to represent the JSON data as a tree
{ DATA =
"ietf-interfaces:interface": {
"name": "GigabitEthernet2", ietf-interfaces:interface
"description": "Wide Area Network", ├── name: GigabitEthernet2
"enabled": true, ├── etc…
"ietf-ip:ipv4": { ├── etc …
"address": [
{
"ip":"172.16.0.2",
"netmask":"255.255.255.0"
}
]
}
}
}
JSON Tree

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Describe these 2 items in one single JSON payload

Device : Cisco ASA Device : User-Mktg-1


Type : Firewall type : workstation
OS : Cisco ASA OS OS : Windows 10
Interface 1 : UP : inside : 192.168.1.254 / 24 Interface 1 : UP : wireless lan : 192.168.1.12 / 24
Interface 2 : UP : outside : 92.34.25.26 / 32 Status : Infected
Interface 3 : Down
Status : Clean

Create a JSON named : devices.json

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Hint : https://jsonlint.com/
Is your JSON valid ? ( 10 mins )
https://jsonlint.com/

Troubleshoot the given example:

devices_wrong.json

( solution : devices.json file )

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Hint : https://jsonlint.com/
Test it into a python Script

See : devices_json.py solution file

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Hint : https://jsonlint
Create your JSON from a python dictionary
• See
• devices_json_directory_to_python.py

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Challenge – 6 (30 mins )
• Copy the JSON result located here :
• https://jsonplaceholder.typicode.com/photos

• Copy it as json.json into your laptop


• Create a script named challenge-6.py which loads the JSON file and create a csv file
named photo.csv with the following format :

• id ; title ; url;thumbnailUrl

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
The python requests
module

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Using Python “requests” Library
• The de facto standard for making HTTP requests in Python
• Install it in the venv with: pip install requests
• Import it in your Python code with “import requests” and then use it
url='http://bru-n9k3-1.cisco.com/ins'
switchuser='admin' response = requests.post(url,data=json.dumps(payload),
switchpassword='cisco!123'
headers=myheaders,auth=(switchuser,switchpasswor
myheaders={'content-type':’application/json'} d))
payload={
"ins_api": { response.status_code # returns the status code as integer
"version": "1.0", response.text # returns the data as string
"type": "cli_conf", response.json() # convert the data into dictionary
"chunk": "0", response.headers # returns the headers
"sid": "1",
"input": "conf ;vlan 126 ;name api_test_126",
"output_format": "json"
}
}
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Install and Import the requests module
Use the request module in
>>> import requests
order to make your script to act >>> requests.get('https://google.com')
as an HTTP Client <Response [200]>

>>> response = requests.get('https://google.com')


>>> response.status_code
200

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Request: GET https://api.ciscospark.com/v1/people/me
Review:
Request/Response Response: 200 OK + Data
HTTP Request GET /v1/people/me HTTP/1.1
Host: api.ciscospark.com
Authorization: Bearer <redacted>
Request Headers Accept: */*
Accept-Encoding: gzip, deflate, sdch
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/49.0.2623.112 Safari/537.36

HTTP Response HTTP/1.1 200 OK


Date: Fri, 08 Apr 2016 16:59:20 GMT
Content-Type: application/json;charset=UTF-8
Content-Encoding: gzip
Response Headers Content-Length: 323
Trackingid: NA_514181f9-7885-4716-bbfb-fe9a54f2248a
Vary: Accept-Encoding
X-Cf-Requestid: 8634487a-8c9e-417e-60bf-06ead6ffe950
<blank line> {
"id": "Y2lzY29zcGFyazovL3VzL1BFT1BMRS9mZjhlZTZmYi1hZmVmLTRhNGQtOTJiMS1kNmIyMTZiNTg5NDk",
"emails": [ "chrlunsf@cisco.com" ],
Response Payload "displayName": "Chris Lunsford (chrlunsf)",
"avatar": "https://1efa7a94ed216783e352-
c62266528714497a17239ececf39e9e2.ssl.cf1.rackcdn.com/V1~ba1ecf557a7e0b7cc3081998df965aad~cNFKqEjAQ5aQ
kyt_l1zsCQ==~1600",
Note: This is all exchanged as simple text "created": "2012-06-15T20:36:48.914Z”
over a TCP/TLS connection. }

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s do a Lab

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Challenge – 7 (5 mins )
• Use requests library in order to retrieve the html content of the url here under and store it
into a test file.
https://www.google.com
• And just display it on the screen
• Or Save the result in a resulting file

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Challenge – 8 (10 mins )
• Start from the challenge-5 but instead of reading the JSON file from the disk, download it
from it’s INTERNET location.
• Get JSON result located here :
• https://jsonplaceholder.typicode.com/photos

• Copy it as json.json into your laptop


• Create a script named challenge-5.py which must return the title of the item for which you
entered the number, when you call the script in CLI

• Ex : python challenge-5.py 3456

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Application Programming
Interface

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
REST APIs

• Mechanism by which clients can communicate with the


REST Server
• HTTP Calls (GET, PATCH, DELETE, POST)

HTTP Request

JSON Response

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
REST Web service
What is REST?
–REpresentational State Transfer
(REST)
–API framework built on HTTP

What is a REST Web Service?


–REST is an architecture style for
designing networked applications.
–Popular due to performance, scale,
simplicity, and reliability
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public

152
How it works ?
REST Restful Request to API
PATCH /v1/groups/b077d6bc-bbdf-42f7-8838-a06053fbd98a

Contains JSON Payload


{"windows_policy_guid":"89912c9e-8dbd-4c2b-a1d8-dee8a0c2bb29"}

JSON Response
{
"version": "v1.0.0",
"metadata": {
"links": {
"self": "https://api.amp.cisco.com/v1/version"
}
},
"data": {}
}
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Dealing with API is dealing with

The API Endpoint

REST Verbs

Variables to pass

Authentication

Error Code Management


© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
The API Endpoint
api_url = {API version}
https:// { device Management IP /}api/com/v5 /object/networks /{object_id}

{host} {base URL} {api_path}

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
With APIs, you can

Create

Read

Update

Delete

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Query Parameters ( ex : GET Method )
https://maps.googleapis.com/maps/api/geocode/json?address=sanjose&limit=10

Server or Host Resource Parameters

• Parameters
• Details to scope, filter, or clarify a
request. Often optional.

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Sending and Receiving Data
• Data can be contained in the • Body_payload
• {
body • 'title': 'Hamlet',
'author': 'Shakespeare'
POST, PUT, PATCH requests

• • }
typically include data in the
header
• GET responses will include data
in the URL
• Format typically JSON or XML
• Check “Content-Type” header

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Pass Data in the HTTP Headers:

Header Example Value Purpose


Content-Type application/json Specify the format of the data in the body
Accept application/json Specify the requested format for returned data
Authorization Basic dmFncmFudDp2YWdyYW50 Provide credentials to authorize a request
Date Tue, 25 Jul 2017 19:26:00 GMT Date and time of the message

• A lot of Security Solution use custom headers for authentication or other purpose

• Header is frequently used to pass query parameters between client and server

• Included in both REQUEST and RESPONSE

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Example : GET FDM Network Objects

api_url=f" https:// {host} : {FDM_PORT} /api/fdm/v{version} {url} ?offset= {offset} & limit= {limit} "

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
HTTP Authentication
• None: The Web API resource is public, anybody can place call.
• Basic HTTP: A username and password are passed to the server in an
encoded string.
• Authorization: Basic ENCODEDSTRING ( username:password )

• Token: A secret generally retrieved from the Web API developer portal.
Keyword (such as, a token) is API dependent.
• Authorization: Token aikasf8adf9asd9akasdf0asd

• OAuth: Standard framework for a flow to retrieve an access token from an


Identity Provider.
• Authorization: Bearer 8a9af9adadf0asdf0adfa0af

• Authorization can be short-lived and require refreshing of tokens


© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Response Status Codes ( Did the call worked ? )

Status Code Status Message Meaning


200 OK All looks good
201 Created New resource created
400 Bad Request Request was invalid
401 Unauthorized Authentication missing or incorrect
403 Forbidden Request was understood, but not allowed
404 Not Found Resource not found
500 Internal Server Error Something wrong with the server
503 Service Unavailable Server is unable to complete request

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
REST API Tools

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Many Options for Working with REST APIs

• curl
• Linux command line application

• Postman
• API testing application and framework

• Requests
• Python library for scripting

• OpenAPI/Swagger
• Dynamic API Documentation

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
How do we know about
Product APIs ?

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
In the API Documentation ( API explorer / Swagger)

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s do a Lab

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s use Webex Teams APIs
Your Goal !
• Send an Hello Message to our Webex Team Room !

© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Sign UP to webex team

• https://teams.webex.com/signin
Where to start ?
• https://developer.webex.com/
Webex Team API Documentation
• https://developer.webex.com/docs/api/getting-started
With Webex Team APIs, you can

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
With Webex Team APIs, you can

Create

Read

Update

Delete
With Webex Team APIs, you can

Create

Read

Update

Delete
Example :
Send a message to a webex team room
• 1 - Use Your Bearer Token.
• 2 - Select a target RoomID where to send your message
• 3 - Enter a text ( In the Text Field or in the Markdown Field )
• 4 - Send your message
Your Bearer Token
Send a message to a webex team room
https://developer.webex.com/docs/api/v1/messages/create-a-message
Send a message to a webex team room
https://developer.webex.com/docs/api/v1/messages/create-a-message
Send a message to a webex team room
https://developer.webex.com/docs/api/v1/messages/create-a-message
Send Your Message
https://developer.webex.com/docs/api/v1/messages/create-a-message

SEND AN HELLO MESSAGE TO OUR ROOM


Postman Lab Time
Your Goal !

• Use Postman to !
• Send an Hello Message to our Webex Team Room !
C) Using Postman - Overview Environment
(Variables)
Collections
(Saved API Calls)
Verb URI

Status Code

Response
Python Lab Time
Your Goal !
• Use Python to !
• Send an Hello Message to our Webex Team Room !

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab resources
• https://github.com/pcardotatgit/python_challenges/tree/master/Prep
aration_challenges_for_Threat_Hunting_Mission/5-
Create_a_Webex_Team_room_and_Send_Message_into_it

• Copy and paste the python 3-send_message.py files

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to call Webex Team REST
APIs ?

© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to call Webex Team API ?
https://webexapis.com/v1/rooms
base path
( old : https://api.ciscospark.com/v1/messages )
What to do ?
https://github.com/pcardotatgit/Webex_Team_Quick_Start/tree/master/1_http_requests

• 1 – Create a New Room


• 1-create_a_room.py
• 2 – Get Room Ids
• 2-list_rooms.py
• 3 – Send a message to the new room
• 3-send_message.py
• 4 – Delete the room
Key Takeaways:
• REST API uses HTTP(S) to send requests and receive responses
• It is very crucial to refer to the API Documentation to understand
what and how to make an API call
• REST APIs use standard verbs like GET, PUT, POST, and DELETE
that correspond to CRUD Operations (Create, Read, Update, Delete)
• Tools like curl, Postman, and Python requests are commonly used
for testing/developing using REST API calls

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

You might also like