Skip to main content

Hypertext Protocol (HTTP): 2. Build an API Client

Hypertext Protocol (HTTP)
2. Build an API Client
    • Notifications
    • Privacy
  • Project HomeTools and Techniques in Software Engineering
  • Projects
  • Learn more about Manifold

Notes

Show the following:

  • Annotations
  • Resources
Search within:

Adjust appearance:

  • font
    Font style
  • color scheme
  • Margins
table of contents
  1. Client-Server Communication
  2. Introduction to Hypertext Protocol (HTTP)
  3. 1. Specifications
  4. 2. Build an API Client
  5. 3. NASA Astronomy Picture of the Day
  6. 4. Python Flask
  7. 5. Bibliography

Building an API Client

We'll be using Python for this example. First we begin with an introduction to the Python Language.

Python3 Syntax

This language was created by Guido van Rossum in the early 90s and has since become one of the most popular languages. This language is a white space language that depends on indentation, it does not use curly braces to denote code blocks. There are lots of uses for this language. Lots of people use it for pseudocode, and lots of people use it for data science and web scraping, and much more.

The following examples for Python 3 syntax come from Learn X in Y Minutes.

# Single line comments start with a hash

# 1. Primitive Datatypes and Operators
# --------------------------------------------------

3   # numbers

# Math
1 + 1 # =>2
8 - 1   # => 7
10 * 2  # => 20
35 / 5  # => 7.0

# The result of division is always a float
10.0 / 3  # => 3.3333333333333335

# Enforce precedence with parentheses
(1 + 3) * 2  # => 8

# Boolean values are primitives (Note: the capitalization)
True
False

# negate with not
not True   # => False
not False  # => True

# Strings are created with " or '
"This is a string."
'This is also a string.'

# A string can be treated like a list of characters
"This is a string"[0]  # => 'T'

# You can find the length of a string
len("This is a string")  # => 16

This next block of code shows some more that you can do with storing values in data structures.

# 2. Variables and Collections
# --------------------------------------------------

# Python has a print function
print("Hello World")

# Lists store sequences
li = []

# Add stuff to the end of a list with append
li.append(1)    # li is now [1]

# Access a list like you would any array
li[0]   # => 1

# Dictionaries store mappings from keys to values
empty_dict = {}
# Here is a prefilled dictionary
filled_dict = {"one": 1, "two": 2, "three": 3}

And finally, this section shows how control statements look like.

# 3. Control Flow and Iterables
# --------------------------------------------------

# Let's just make a variable
some_var = 5

# Here is an if statement. Indentation is significant in Python!
# Convention is to use four spaces, not tabs.
# This prints "some_var is smaller than 10"
if some_var > 10:
    print("some_var is totally bigger than 10.")
elif some_var < 10:    # This elif clause is optional.
    print("some_var is smaller than 10.")
else:                  # This is optional too.
    print("some_var is indeed 10.")

"""
For loops iterate over lists
prints:
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    # You can use format() to interpolate formatted strings
    print("{} is a mammal".format(animal))

Reference:

  • Learn Python in Y Minutes https://learnxinyminutes.com/docs/python3/

Python Resources:

  • Python Software Foundation (PSF) describes moving from other languages: \ https://wiki.python.org/moin/MovingToPythonFromOtherLanguages
  • Learn Python the Hard Way https://learnpythonthehardway.org/book/
  • Python for Java Programmers http://python4java.necaiseweb.org/Main/TableOfContents
  • Python Cheatsheet \ https://github.com/akashp1712/pythoncheatsheets/blob/master/pythonforjavadevelopers1_1.pdf

Examples of using Python to connect to an API

  • https://github.com/bc-cisc3140-mw2-fall2019/cisc3140/tree/master/python_app
  • https://colab.research.google.com/drive/1vaOAgWYKo44o6drJKGeidPEZWMDWk9eE

There are many ways to implement an API client. Here is a quick guide for creating an API client with Python. Using Python to access NASA Picture of the Day:

# nasa.py

import urllib.request
import json

# The API endpoint url
url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'

# Request the url
urlobj = urllib.request.urlopen(url)

# Read the request object
apodread = urlobj.read()

# Decode the data into types that Python understands
data = json.loads(apodread.decode('utf-8'))

Annotate

Next Chapter
3. NASA Astronomy Picture of the Day
PreviousNext
Web Technology
Powered by Manifold Scholarship. Learn more at
Opens in new tab or windowmanifoldapp.org