04 Building RESTful Services
04 Building RESTful Services
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
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
@JohnRofrano 4 https://www.nginx.com/blog/introduction-to-microservices/
Before we get started
... how does http work?
@JohnRofrano 5
Building RESTful Services
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:
make="Mercedes-Benz"&model="C-Class"&year="2017"
@JohnRofrano 8
Building RESTful Services
of an HTTP/1.1 200 OK
HTTP Header:
•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
http://www.car-reviews.com/reviews/sedans?min_rating=good
@JohnRofrano 10
Building RESTful Services
@JohnRofrano 11
Building RESTful Services
Path Parameters
/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?
@JohnRofrano 16
fi
fi
fi
Building RESTful Services
@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?
REST Architecture
What is a Resource
@JohnRofrano 22
fi
Building RESTful Services
HEAD Asks for a response identical to a GET request, but without the response body
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
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 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
@JohnRofrano 25
Building RESTful Services
Amazon S3 Buckets
Consider Amazon’s Simple Storage Service (AWS S3)
@JohnRofrano 26
Building RESTful Services
• 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
Stateless Applications
@JohnRofrano 30
Building RESTful Services
• 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
@JohnRofrano 33 From: REST API Design Rulebook by Mark Masse, Publisher: O'Reilly Media, Inc.
Building RESTful Services
@JohnRofrano 34
Building RESTful Services
@JohnRofrano 35
Building RESTful Services
@JohnRofrano 36
Building RESTful Services
• 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
@JohnRofrano 39
Building RESTful Services
Side-Effects
@JohnRofrano 40
ff
Building RESTful Services
@JohnRofrano 41
Building RESTful Services
@JohnRofrano 42
Building RESTful Services
@JohnRofrano 43
idem•po•tent
@JohnRofrano 44
ff
fi
Building RESTful Services
Idempotence
@JohnRofrano 45 From: REST in Practice, by Savas Parastatidis, Jim Webber, Ian Robinson,Publisher: O'Reilly Media, Inc.
ffi
Building RESTful Services
Safety
@JohnRofrano 46 From: REST in Practice, by Savas Parastatidis, Jim Webber, Ian Robinson,Publisher: O'Reilly Media, Inc.
f
ff
Building RESTful Services
{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'bearer %s' % token
}
@JohnRofrano 47
Building RESTful Services
• 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
@JohnRofrano 49
Building RESTful Services
PUT http://api.myapp.com/user-group/123
{
...
status: "disabled"
}
@JohnRofrano 50
Building RESTful Services
@JohnRofrano 51
ff
ff
fi
fi
ff
Building RESTful Services
Actions as A URI
PUT http://api.myapp.com/servers/123/reboot
@JohnRofrano 52
Building RESTful Services
• 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
PUT /recommendations/{id}/like
PUT /shopcarts/{id}/clear
PUT /orders/{id}/cancel
PUT /payments/{id}/refund
@JohnRofrano 54
Building RESTful Services
• 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
• 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
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
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
@JohnRofrano 59
Building RESTful Services
GitLab
Example
@JohnRofrano 60
Building RESTful Services
@JohnRofrano 62
Building RESTful Services
app = Flask(__name__)
COUNTERS: dict = {}
@app.route("/", methods=["GET"])
def index():
"""Root URL"""
return {"status": "OK"}
@JohnRofrano 63
Building RESTful Services
@JohnRofrano 64
Building RESTful Services
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
@JohnRofrano 66
Building RESTful Services
@JohnRofrano 67
Building RESTful Services
if name in COUNTERS:
del COUNTERS[name]
@JohnRofrano 68
Hands-On
“live session”
@JohnRofrano 69
Building RESTful Services
@JohnRofrano 71
Building RESTful Services
• 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
@JohnRofrano 73
Building RESTful Services
@JohnRofrano 74
Building RESTful Services
• 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