Make HTTP requests using curl
, the browser address bar, and AJAX for:
- A resource collection.
- A specific resource.
Use response data in future requests
Set up the client:
- Fork and clone this repository.
- Create and checkout a new branch (training).
- Install dependencies with
npm install
.
We'll make requests of and receive responses from an HTTP server we'll set up together:
- Open a new terminal (window or tab).
- Change into
~/wdi/tmp
. - Fork and clone library-api and follow installation instructions listed there.
- Once installed, checkout a
jquery-ajax
branch withinlibrary-api
.
We're now ready to make requests.
What's in a name?
AJAX at MDN.
The jQuery.ajax() interface.
- URL structure
- Request verbs
- HTTP request and response
Retrieve a list of books from the API
Entering http://localhost:3000/books
into the chrome address bar.
If not already installed in chrome, let's add a JSON formatting utility.
curl
is a command line utility for making http requests. We'll use curl to
retrieve the book collection.
Let's write that curl command into a script.
We'll take a stepped approach:
- Add a form to
index.html
. - Add a submit input to the form.
- Add a submit handler to the form in the document ready event in
assets/scripts/index.js
. - Add a collection success and fail handler to
assets/scripts/ui.js
. - Add a book collection retrieval method to
assets/scripts/library-api.js
. - Invoke the collection retrieval method from the submit handler passing the success and fail callbacks.
The A in AJAX stands for asynchronous. Let's explore some implications of asynchronous behavior.
Retrieve a book from the API
Entering http://localhost:3000/books/1
into the chrome address bar.
Entering http://localhost:3000/books/<integer>
into the chrome address bar.
We'll use curl to retrieve the one book at a time.
Let's write that curl command into a script.
Again, take a stepped approach:
- Add a text input for a book id to the form in
index.html
. - Retrieve the value of the id, if any, in the submit handler.
- Branch on that value in the submit handler.
- Add a single book success and fail handler to
assets/scripts/ui.js
. - Add a single book retrieval method to
assets/scripts/library-api.js
. - Invoke the single book retrieval method from the submit handler passing the success and fail callbacks.
Source code distributed under the MIT license. Text and other assets copyright General Assembly, Inc., all rights reserved.