Representational State Transfer (REST) and JavaScript Object Notation (JSON)
Preparation
W3Schools’s JSON Tutorial
Understanding and Using REST APIs
Learning Objectives
- Create JSON representations of data (particularly arrays and objects)
- Compare and contrast JSON and XML as data formats
- Describe the benefits of REST as an architectural style
- Use and implement a simple REST service
Practice
Experiment with an example REST API for a library database.
- Download the library database script and REST API
- Execute the
library.mysql.sql
script using MySQL Workbench to create the library database. - Create a subdirectory named
library
in XAMPP’shtdocs
directory. Place the remaining files in thelibrary
directory. - Open
http://localhost/library/client.html
in your web browser. If you receive an HTTP 404 Not Found error, make sure that XAMPP (specifically Apache) is running on your computer. - Submit a GET request to
http://localhost/library/api/books
. Examine the response status and content. Do you understand each? - Submit a GET request for a particular book using resource URI provided in the response to the prior request. How is the book identified? Can you provide the structure of the resource URI?
-
Submit a POST request to
http://localhost/library/api/books
to create the following entry:- ISBN
- 9781119231509
- Title
- Cybersecurity Law
- Author
- Jeff Kosseff
- Copyright
- 2017
- Publisher
- John Wiley & Sons, Inc.
You must provide this information as JSON as part of of the request body. The format is the same as that returned by a GET request for a specific book. Does the new entry appear when you submit another request that lists all the books?
- Open
api/books.php
. Examine the source code to see how the REST API is implemented. Add support for the PATCH and PUT methods and test both.