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

04 Building RESTful Services

Uploaded by

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

04 Building RESTful Services

Uploaded by

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

Building RESTful

Services
with Python and Flask
CSCI-GA 2820, Graduate Division, Computer Science

Instructor:
John J Rofrano
Senior Technical Staff Member | DevOps Champion
IBM T.J. Watson Research Center
[email protected] (@JohnRofrano)
1

@JohnRofrano
Building RESTful Services

Source for This Lab

• Start Docker Desktop


• The source for this lab can be found on GitHub at:

git clone https://github.com/nyu-devops/lab-simple-rest.git

cd lab-simple-rest

code .

@JohnRofrano 2
Building RESTful Services

Objectives
The objectives of this class are to:
- Understand what a REST API is
- Understand the Guidelines and
Best Practices
- How to build a more RESTful
service
- How to use Python with Flask to
build a REST API

@JohnRofrano 3
Building RESTful Services

Cloud Native Applications


• The Twelve-Factor App describes patterns for
cloud-native architectures which leverage
microservices.
• Applications are designed as a collection of
stateless microservices.
• State is maintained in separate databases and
persistent object stores.
• Resilience and horizontal scaling is achieved
through deploying multiple instances.
• Failing instances are killed and re-spawned, not
debugged and patched.
• DevOps pipelines help manage continuous
delivery of services.

@JohnRofrano 4 https://www.nginx.com/blog/introduction-to-microservices/
Before we get started
... how does http work?

@JohnRofrano 5
Building RESTful Services

HyperText Transfer Protocol


• The Internet is a collection of servers that have
resources (e.g., html pages, databases, etc.)
• These resources can be static web pages or they
can be applications
• Application resources usually serve up resources
that are stored in a database
• Web resources can be accessed via a program or
web browser
• The HyperText Transport Protocol (HTTP) is how GET
web browsers talk to servers POST
PUT
PATCH
(https://www.ietf.org/rfc/rfc2616.txt) Methods
DELETE
OPTIONS
...

@JohnRofrano 6 [Source: http://www.ic.unicamp.br/~921234/IntroZope/slide-04.html]


Building RESTful Services GET https://www.edmunds.com/car-reviews

Example
Web Form

@JohnRofrano 7
Building RESTful Services POST https://www.edmunds.com/car-reviews

Anatomy URL:

of an https://www.edmunds.com/car-reviews

HTTP Header:

Request POST /car-reviews HTTP/1.1


User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.edmunds.com
An HTTP request
Content-Type: application/x-www-form-urlencoded
consists of a: Content-Length: 48
•URL Accept-Language: en-us
Accept-Encoding: application/json
•Header
Connection: Keep-Alive
•Body
Body:

make="Mercedes-Benz"&model="C-Class"&year="2017"

@JohnRofrano 8
Building RESTful Services

Anatomy Return Code:

of an HTTP/1.1 200 OK

HTTP Header:

Response Date: Sun, 23 Feb 2020 18:44:35 GMT


Cache-Control: private, max-age=0
X-Frame-Options: SAMEORIGIN
An HTTP response Content-Type: application/json
consists of a: Content-Length: 1048
•Return Code
•Header Body:

•Body {
id: "278449015",
make: "Mercedes-Benz",
model: "C-Class",
year: 2017,
overall_rating: 4.5,
reviews: ["Nice ride", "Great looks", "..."]
}

@JohnRofrano 9
Building RESTful Services

Parts of a URL

• A Uniform Resource Locator points to a resource or collection of resources


• It is made up of a protocol, host name, and optional path, and query string

http://www.car-reviews.com/reviews/sedans?min_rating=good

Protocol Host name Path Query String

@JohnRofrano 10
Building RESTful Services

Types of URL Parameters

• Parameters are additional data that you need to pass in to


qualify the request
• There 3 parameter types
- Path parameters
- Query parameters
- Header parameters (more like metadata)

@JohnRofrano 11
Building RESTful Services

Path Parameters

• Can be used to identify a particular resource


• The value of the parameter is passed in to the operation by the HTTP client as a
variable part of the URL path
• For example, the customer ID can be passed in as a path parameter named
customer_id:

/customers/{customer_id}

@JohnRofrano 12
Building RESTful Services

Query Parameters

• The value of a query parameter is passed in to the operation by the HTTP client
as a key value pair in the query string at the end of the URL
• Query parameters are separated from the URL path by a question mark {?} and
multiple parameters are delimited by an ampersand {&}
• As an example, query parameters can be used to pass in a lter to be applied to
the results that should be returned by a particular operation:

/customers?city=Middletown&state=NY

@JohnRofrano 13

fi
Building RESTful Services

Header Parameters

• The HTTP client can pass header parameters to an operation by adding them as
HTTP headers in the HTTP request
• Headers are additional metadata that is sent with the request but not part of the
URL
• As an example, header parameters might be used to pass in a unique identi er
that identi es the HTTP client that is calling the operation:

X-Client-Id: a8c4cb0c-500e-11ea-bc47-acde48001122

@JohnRofrano 14
fi
fi
AND NOW BACK TO
OUR REGULARLY
SCHEDULED
PROGRAM
15
Building RESTful Services

What is an API?

• Application Programming Interface


• A documented way to interact with a
program or service
• De nes the requests that you can make
of the service
• De nes the data that you can
interchange with the service
• De nes the results that will be returned
by the service

@JohnRofrano 16
fi
fi
fi
Building RESTful Services

Every VCR and DVD Player has the same interface


API
Analogy

@JohnRofrano 17
“Microservices need a consistent way of
communicating.”

@JohnRofrano 18
Building RESTful Services

REST
Architecture
and RESTful
Services

@JohnRofrano 19
Building RESTful Services

What is REST?

• Roy Fielding’s 2000 PhD thesis, Architectural Styles and the


Design of Network-based Software Architectures
• REpresentational State Transfer
- A REST API describes a set of resources
- A simple way to transfer and manipulate the state of a resource
• A service based on REST is called a RESTful service
• A RESTful service is exposed through a Uniform Resource
Identi er (URI)
• A client would issue a Hypertext Transfer Protocol (HTTP) request
to manipulate it
@JohnRofrano 20
fi
Building RESTful Services

REST Architecture

• REST is a client-server architecture


- The client and the server provide a separation of concerns which allows both the client and the server to
evolve independently as it only requires that the interface stays the same
• REST is stateless
- The communication between the client and the server always contains all the information needed to
perform the request. There is no session state in the server.
• REST is cacheable
- The client, the server can cache resources in order to improve performance
• REST provides a uniform interface between components
- All components follow the same rules to speak to one another
• REST is a layered system
- Individual components cannot see beyond the immediate layer with which they are interacting
@JohnRofrano 21 https://ninenines.eu/docs/en/cowboy/2.6/guide/rest_principles/
Building RESTful Services

What is a Resource

• The fundamental concept in any RESTful API is


the resource
• A resource is an object with a type, associated data,
relationships to other resources, and a set of methods that
operate on it
• Only a few standard methods are de ned for the resource
corresponding to the standard HTTP GET, POST, PUT and
DELETE methods

@JohnRofrano 22
fi
Building RESTful Services

HTTP Request Methods

HEAD Asks for a response identical to a GET request, but without the response body

CONNECT Establishes a tunnel to the server identi ed by the target resource

GET Requests a representation of the speci ed resource. Requests using GET should only retrieve data

POST Submits an entity to the speci ed resource, often causing a change in state or side e ects on the server

PUT Replaces all current representations of the target resource with the request payload

PATCH Applies partial modi cations to a resource

DELETE Deletes the speci ed resource

OPTIONS Describes the communication options for the target resource

TRACE Performs a message loop-back test along the path to the target resource

@JohnRofrano 23
fi
fi
fi
fi
fi
ff
Building RESTful Services

REST API Conventions

• REST API conventions de ne speci c behavior for each type of HTTP method.
Use the following guidelines as a starting point for designing your API.
HTTP Verb Example URI Function Description

GET /orders List Returns all of the orders in the database (should be ltered by a
query string)

POST /orders Create Create a new order, and upon success, receive a Location
header specifying the new order’s URI.

GET /orders/{order_id} Read Request the current state of the order speci ed by the URI

PUT /orders/{order_id} Update Update an order at the given URI with new information,
providing the full representation

DELETE /orders/{order_id} Delete Remove the order identi ed by the given URI from the database

@JohnRofrano 24
fi
fi
fi
fi
fi
Building RESTful Services

GitLab REST API Example


https://docs.gitlab.com/ee/api/rest/#status-codes

@JohnRofrano 25
Building RESTful Services

Amazon S3 Buckets
Consider Amazon’s Simple Storage Service (AWS S3)

Purpose HTTP Request Method Name

Create an object in my bucket POST my-bucket.s3.amazonaws.com CreateObject

View objects in my bucket GET my-bucket.s3.amazonaws.com ReadObject

Change an object in my bucket PUT my-bucket.s3.amazonaws.com UpdateObject

Remove an object from my bucket DELETE my-bucket.s3.amazonaws.com DeleteObject

@JohnRofrano 26
Building RESTful Services

A REST API describes a set of resources

• Example REST API for Customer resource

Resource Path Description

/customers All the customers in the database

/customers/123 Customer #123

/customers/123/orders All orders for customer #123

/customers/123/orders/45 Order #45 for customer #123


@JohnRofrano 27
Building RESTful Services

What Does Resource Based Mean?

• Things vs Actions
• Nouns vs Verbs
• Not a Remote Procedure Call mechanism
• Everything is Identi ed by URI’s
- Multiple URI’s can manipulate the same Resource using
di erent HTTP Verbs

@JohnRofrano 28
ff
fi
Building RESTful Services

Resources Represented as JSON

• While XML is a valid representation,


JSON is more popular
• In JSON, just three types of data exist:
- scalar (number, string, boolean, null).
- array
- object
{
name: "John Smith",
rating: 24,
address: "123 Main St, Buffalo, NY",
birthDay: "1990-10-05"
}
Images from http://www.json.org/
@JohnRofrano 29
Building RESTful Services

Stateless Applications

• Server maintains no client state


• Each request contains enough context to process the
message
• Any application state must be held on the client side
• Allows easy horizontal scaling of application services

@JohnRofrano 30
Building RESTful Services

What REST is Not

• REST is not a Remote Procedure Call (RPC) or just a bunch of verbs as URI’s
• For example, these are NOT RESTful API’s:
GET http://api.myapp.com/getUser/123
POST http://api.myapp.com/addUser
GET http://api.myapp.com/removeUser/123
• These are the RESTful equivalents:
GET http://api.myapp.com/users/123
POST http://api.myapp.com/users
DELETE http://api.myapp.com/users/123

@JohnRofrano 31
Building RESTful Services

REST API
Guidelines

@JohnRofrano 32
Building RESTful Services

Guidelines for Well Formed URI’s

• A plural noun should be used for collection names


- e.g., /users not /user
• A singular noun should be used for document names
- e.g., /users/123/agreement
• Variable path segments may be substituted with identity-based values
- e.g., /users/123/addresses/2
• CRUD function names should not be used in URIs
- e.g., never use: /getUsers/123

@JohnRofrano 33 From: REST API Design Rulebook by Mark Masse, Publisher: O'Reilly Media, Inc.
Building RESTful Services

URI Format Guidelines

• Forward slash separator (/) must be used to indicate a hierarchical relationship


http://api.myapp.com/users/{id}/addresses
• A trailing forward slash (/) should not be included in URIs
http://api.myapp.com/users/ <— not recommended
http://api.myapp.com/users <— recommended
• Hyphens (-) should be used to improve the readability of URIs
http://api.myapp.com/userGroups <— not recommended
http://api.myapp.com/user-groups <— recommended

@JohnRofrano 34
Building RESTful Services

URI Format Guidelines (cont)

• Underscores (_) should not be used in URIs


http://api.myapp.com/user_groups <— not recommended
http://api.myapp.com/user-groups <— recommended
• Lowercase letters should be preferred in URI paths
http://api.myapp.com/Groups/Reset <— not recommended
http://api.myapp.com/groups/reset <— recommended
• File extensions should not be included in URIs
http://api.myapp.com/users/123/adresses.json <— not recommended
http://api.myapp.com/users/123/adresses <— recommended

@JohnRofrano 35
Building RESTful Services

RESTful API for USER Resource

• Using the example of a User as a resource the API would be:

GET /users <— retrieve a list of Users


GET /users?state="ny"<— retrieve a list of Users with a
state of "ny"
GET /users/123 <— retrieves the User with Id 123
POST /users <— creates a new User
PUT /users/123 <— updates the User with Id 123
DELETE /users/123 <— deletes the User with Id 123

@JohnRofrano 36
Building RESTful Services

What About Subordinates

• Subordinate resources can be addressed with multiple resources and ids in the
URI:

GET /resource/{id}/subordinate/{id}

• Example: A Order has multiple Items. To manipulate item with id=2 use:
POST /orders/123/items <- CREATE an item in order 123
GET /orders/123/items/2 <- READ item 2 from order 123
PUT /orders/123/items/2 <- UPDATE item 2 in order 123
DELETE /orders/123/items/2 <- DELETE item 2 from order 123

@JohnRofrano 37
Building RESTful Services

Correct use of
HTTP Verbs

@JohnRofrano 38
Building RESTful Services

Read with GET

• Use HTTP GET verb to Read a Resource


- GET /products/123
- Should return the product with an id of 123
• Successful return codes:
- 200_OK: If a resource exists and can be read by the server and returned.
- 404_NOT_FOUND: If the resource doesn't exist

@JohnRofrano 39
Building RESTful Services

Side-Effects

• GET must NEVER modify the resource


- Never code: GET https://api.del.icio.us/posts/delete

• GET must have no side-e ects (see above)


• GET should return a representation of the resource(s) it was called on… period!

@JohnRofrano 40
ff
Building RESTful Services

Create with POST

• Use HTTP POST verb to Create a Resource


• Successful return codes:
- 201_CREATED: If a resource has been created on the origin server, the
response SHOULD be 201 (Created) and contain an entity which describes the
status of the request and refers to the new resource, and a Location header
- 202_ACCCEPTED: If the resource takes a long time to create you may return
202 (Accepted) with a Location header to check the status of the creation

@JohnRofrano 41
Building RESTful Services

Update with PUT

• Use HTTP PUT verb to Update a Resource


- PUT /products/123
- Should update the product with an id of 123 with the new data
• Successful return codes:
- 200_OK: If a resource exists and can be updated by the server and returned.
- 404_NOT_FOUND: If the resource doesn't exist

@JohnRofrano 42
Building RESTful Services

Delete with DELETE

• Use HTTP DELETE verb to Delete a Resource


- DELETE /products/123
- Should delete the product with an id of 123
• Successful return codes:
- 204_NO_CONTENT: If a resource exists and can be deleted by the server or if
the resource cannot be found (which means it's already deleted)

@JohnRofrano 43
idem•po•tent

An action when, when performed multiple times, has


no further e ect on its subject after the rst time it is
performed

@JohnRofrano 44
ff
fi
Building RESTful Services

Idempotence

• PUT and DELETE operations are idempotent


• If you DELETE a resource, it’s gone. If you DELETE it again, it’s still gone (i.e., do
not throw a 404 Not Found error!)
• Some systems might want to send a 404 on DELETE if the original resource never
existed (but this could be di cult to prove)
• If you use PUT to change the state of a resource, you can resend the PUT request
and the resource state should remain the same.

@JohnRofrano 45 From: REST in Practice, by Savas Parastatidis, Jim Webber, Ian Robinson,Publisher: O'Reilly Media, Inc.
ffi
Building RESTful Services

Safety

• While GET means "Read"… (and is safe)


• POST is neither safe nor idempotent
• Making two identical POST requests to a resource will probably result in creating
two resources containing the same information
• With overloaded POST’s that may have di erent behavior based on data passed
in, all bets are o

@JohnRofrano 46 From: REST in Practice, by Savas Parastatidis, Jim Webber, Ian Robinson,Publisher: O'Reilly Media, Inc.
f
ff
Building RESTful Services

Use HTTP Headers

• Information about what to send or accept should be expressed in HTTP headers


• Some examples are:

{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'bearer %s' % token
}

@JohnRofrano 47
Building RESTful Services

The Root URL

• The root url '/' should return helpful information about the API:
200 OK
{
"url": "https://api.spire.io/",
"resources": {
"sessions": {
"url": "https://api.spire.io/sessions"
},
"accounts": {
"url": "https://api.spire.io/accounts"
},
"billing": {
"url": "https://api.spire.io/billing"
}
}
}
@JohnRofrano 48
Building RESTful Services

What About Actions?

• Actions are more like RPC than REST


• REST doesn’t prescribe how to handle actions but there are best practices
• But some times you need to make an action based call on a resource
- e.g., Start, Stop, Reboot, Shutdown, Register, Deregister

@JohnRofrano 49
Building RESTful Services

Actions as State Changes

• Let’s say you want to disable a resource like a user group


• If the resource had a representation of it’s status you could use a PUT request to
change that status
• RESTful Example: Disable UserGroup with id 123

PUT http://api.myapp.com/user-group/123
{
...
status: "disabled"
}
@JohnRofrano 50
Building RESTful Services

State Changes that are Ambiguous

• Sometimes, it is required to expose an operation in the API that inherently is non


RESTful
• One example of such an operation is where:
- You want to introduce a state change for a resource
- But there are multiple ways in which the same nal state can be achieved
- And those ways actually di er in a signi cant but non-observable side-e ect.
(e.g. "shutdown" vs "power o " a server)
PUT http://api.myapp.com/servers/123/shutdown
PUT http://api.myapp.com/servers/123/poweroff

@JohnRofrano 51
ff
ff
fi
fi
ff
Building RESTful Services

Actions as A URI

• Let’s say you want to reboot a resource that is running


• If the resource doesn’t have a representation of it’s state that you can change,
you could create a URI for the action
• Example: Reboot server with id 123

PUT http://api.myapp.com/servers/123/reboot

@JohnRofrano 52
Building RESTful Services

Actions as a property mutator

• Let’s say you want to activate and deactivate a user account you can use an
action with an HTTP verb
• To activate a user:

PUT /users/{id}/active

• To deactivate a user:

DELETE /users/{id}/active

@JohnRofrano 53
Building RESTful Services

Actions as a Verb in URI

• More examples of using a verb in the URI as an action

PUT /recommendations/{id}/like

PUT /shopcarts/{id}/clear

PUT /orders/{id}/cancel

PUT /payments/{id}/refund

@JohnRofrano 54
Building RESTful Services

How to Handle Queries

• If the resource is a collection, you can implement a simple query using URL
parameters
• Example: Find all pets that are poodles

GET http://api.myapp.com/pets?breed="poodle"&sort_by=created

@JohnRofrano 55
Building RESTful Services

Create Useful Error Messages

• The more you can tell the client about what went wrong the better
• If there is a required parameter like "name" that is missing:
- Rather than returning an error message that says: 'missing parameter'
- Return more information like: 'required name parameter is missing'
• This will give the caller more information about why their call failed

@JohnRofrano 56
Building RESTful Services

Error Message Example


An example from the twilio api:

GET https://api.twilio.com/2010-04-01/Accounts.json

results in:

401 Unauthorized
WWW-Authenticate: Basic realm="Twilio API"
{
"code": 20003,
"detail": "Your AccountSid or AuthToken was incorrect.",
"message": "Authentication Error - No credentials provided",
"more_info": "https://www.twilio.com/docs/errors/20003",
"status": 401
}
@JohnRofrano 57
Building RESTful Services

Use Proper HTTP Return Codes

200 Indicates that the request was completed successfully. All GET requests that are successful
should return 200

201 Indicates that a record was created successfully. All POST requests that successfully create
a resource should return 201

204 Indicates that a record was deleted successfully. All DELETE requests that completed
successfully should return 204 and the body should be empty.

40X Status codes in the 400 range indicate a client error, such as 400 for invalid request syntax
(401, and 401 Unauthorized for not having proper credentials are probably the most common.
404)
50X Status codes in the 500 range indicate that a server error occurred. The client request may
(500, have been valid or invalid, but a problem occurred on the server that prevented it from
503) processing the request.

@JohnRofrano 58
Building RESTful Services

Responses ( Happy Path )

‣ GET /users ‣ PUT /users/12345


- 200 + Array of Users [{...},{...},{...}] - 200 + User {...}
‣ GET /users/12345 ‣ DELETE /users/12345
- 200 + User {...}
- 204 + empty body
‣ POST /users
- 201 + User {...}
- Location Header for GET

@JohnRofrano 59
Building RESTful Services

GitLab
Example

@JohnRofrano 60
Building RESTful Services

Common REST API Return Codes

Code: 200 (“OK”) should be used to indicate nonspeci c success


Code: 200 (“OK”) must not be used to communicate errors in the response body
Code: 201 (“Created”) must be used to indicate successful resource creation
Code: 202 (“Accepted”) must be used to indicate successful start of an asynchronous action
Code: 204 (“No Content”) should be used when the response body is intentionally empty
Code: 301 (“Moved Permanently”) should be used to relocate resources
Code: 302 (“Found”) should not be used
Code: 303 (“See Other”) should be used to refer the client to a di erent URI
Code: 304 (“Not Modi ed”) should be used to preserve bandwidth
Code: 307 (“Temporary Redirect”) should be used to tell clients to resubmit the request to another URI
Code: 400 (“Bad Request”) may be used to indicate nonspeci c failure
Code: 401 (“Unauthorized”) must be used when there is a problem with the client’s credentials
Code: 403 (“Forbidden”) should be used to forbid access regardless of authorization state
Code: 404 (“Not Found”) must be used when a client’s URI cannot be mapped to a resource
Code: 405 (“Method Not Allowed”) must be used when the HTTP method is not supported
Code: 406 (“Not Acceptable”) must be used when the requested media type cannot be served
Code: 409 (“Con ict”) should be used to indicate a violation of resource state
Code: 412 (“Precondition Failed”) should be used to support conditional operations
Code: 415 (“Unsupported Media Type”) must be used when the media type of a request’s payload cannot be processed
Code: 422 ("Unprocessable entity") must be used if the server can not process the property, for example, if an image cannot be formatted or
if required elds are missing from the payload
Code: 500 (“Internal Server Error”) should be used to indicate API malfunction
@JohnRofrano 61
fi
fl
fi
fi
fi
ff
Let's look at some RESTful Code!

@JohnRofrano 62
Building RESTful Services

Basic Flask App

• This code is called on the URL GET /

from flask import Flask, jsonify, abort, url_for


import status

app = Flask(__name__)

COUNTERS: dict = {}

@app.route("/", methods=["GET"])
def index():
"""Root URL"""
return {"status": "OK"}

@JohnRofrano 63
Building RESTful Services

Create a Counter named foo

• This code is called on the URL POST /counters/foo 201


{
"name": "foo",
@app.route("/counters/<name>", methods=["POST"]) "counter": 0
def create_counters(name):
"""Create a counter"""
}
app.logger.info("Request to Create counter...")
Header:
if name in COUNTERS:
{
abort(status.HTTP_409_CONFLICT, f"Counter {name} already exists.")
"Location": "/counters/foo"
counter = 0 }
COUNTERS[name] = counter

app.logger.info("Counter %s created.", name)


location_url = url_for("read_counters", name=name, _external=True)
return jsonify(name=name, counter=counter), status.HTTP_201_CREATED, {"Location": location_url}

@JohnRofrano 64
Building RESTful Services

List all Counters

200
• This code is called on the URL GET /counters [
{
@app.route("/counters", methods=["GET"]) "name": "foo",
def list_counters(): "counter": 0
"""List counters"""
}
app.logger.info("Request to list all counters...")
]
counters: list = []
for name in COUNTERS:
counters.append({"name" : name, "counter" : COUNTERS[name]})

return counters

@JohnRofrano 65
Building RESTful Services

Update a Counter named foo

• This code is called on the URL PUT /counters/foo 200


{
@app.route("/counters/<name>", methods=["PUT"]) "name": "foo",
def update_counters(name): "counter": 1
"""Update a counter""" }
app.logger.info("Request to Update counter %s...", name)

# Try and get the counter


counter = COUNTERS.get(name)

# Return an error if the counter cannot be found


if counter is None:
abort(status.HTTP_404_NOT_FOUND, f"Counter {name} does not exist")

# Increment the counter


COUNTERS[name] += 1

return jsonify(name=name, counter=COUNTERS[name]), status.HTTP_200_OK

@JohnRofrano 66
Building RESTful Services

Read a Counter named foo

• This code is called on the URL GET /counters/foo 200


{
@app.route("/counters/<name>", methods=["GET"]) "name": "foo",
def read_counters(name: str): "counter": 1
"""Read a counter""" }
app.logger.info("Request to Read counter: %s...", name)

# Try and get the counter


counter = COUNTERS.get(name)

# Return an error if the counter cannot be found


if counter is None:
abort(status.HTTP_404_NOT_FOUND, f"Counter {name} does not exist")

app.logger.info("Returning: %s = %d...", (name, counter))


return jsonify(name=name, counter=counter), status.HTTP_200_OK

@JohnRofrano 67
Building RESTful Services

Delete a Counter named foo

• This code is called on the URL DELETE /counters/foo 204


""
@app.route("/counters/<name>", methods=["DELETE"])
def delete_counters(name):
"""Delete a counter"""
app.logger.info("Request to Delete counter...")

if name in COUNTERS:
del COUNTERS[name]

return "", status.HTTP_204_NO_CONTENT

@JohnRofrano 68
Hands-On
“live session”

@JohnRofrano 69
Building RESTful Services

Some Assembly Required

• Tools you will need to complete this lab:


- Github Account (github.com)
- Git Client
- Visual Studio Code
- Docker
- Vagrant and VirtualBox
- (Optional) JsonView, Simple REST
Client
@JohnRofrano 70
Building RESTful Services

Optional Browser Plugin

• JSON Peep or JsonView — will format


Json output so that even humans can
read it
• Browser extensions for Safari, Chrome,
Firefox
• When working with REST APIs it comes
in handy

@JohnRofrano 71
Building RESTful Services

Optional Browser Plugin

• Simple REST Client allows you to make POST, PUT, DELETE calls in addition to
GET (which your browser can do)

@JohnRofrano 72
Building RESTful Services

Postman REST Client


https://www.getpostman.com

@JohnRofrano 73
Building RESTful Services

Visual Studio: Thunder Client

@JohnRofrano 74
Building RESTful Services

Practice REST Backend

• Reqres.in allows you to make POST, PUT, DELETE calls in with standard
responses to test your rest client https://reqres.in

@JohnRofrano 75
Live Demo

76
Building RESTful Services

Summary
• You should now have a good
overview what a REST API is
• You now know the guidelines for
creating a good RESTful API
• You should also be able to create a
REST API for any Resource using
Python and Flask

@JohnRofrano 77
Building RESTful Services

Additional Reading

• REST API Design Rulebook by Mark Masse, Publisher: O'Reilly Media, Inc.
• RESTful Web Services Cookbook by Subbu Allamaraju, Publisher: O'Reilly
Media, Inc.
• REST in Practice, by Savas Parastatidis, Jim Webber, Ian Robinson,Publisher:
O'Reilly Media, Inc.
• RESTful Web Services, by Sam Ruby, Leonard Richardson, Publisher: O'Reilly
Media, Inc.

@JohnRofrano 78

You might also like