While the previous method, pet.find
allowed us to provide criteria for a search and returned those pets matching the criteria, this method takes a unique id and simply pulls that single pet's record. It doesn't take a whole lot of imagination to think of how this might be used.
If we had an app that allowed users to search for pets and mark some as favorites to review later we could easily implement the search with the pet.find
method. Once they found a few and marked them as favorites, we would want to keep track of them.
Here we would have a few options. One would be to store a snapshot of the data the pet.find
call gave us for that pet. This, however, may not be the best since that data may not be current a day or two later, especially if the pet were to be adopted.
A much better idea would be to store the favorited pet's id number and then use the pet.get
method to refresh the pets info next time the user wants to view that pet. This ensure up to date information is provided!
Name | Type | Required? | Description |
---|---|---|---|
key | string | required | your developer key |
token | string | optional | session token |
id | integer | required | pet ID |
format | string | optional (default=xml) | Response format: xml, json |
To see this in action I have created a small app below that pulls 4 pets and allows you to mark them as favorites. Below the results is a button for you to press that will pull only your favorites and display them in another section
We first have a Map that holds all the id numbers for our favorited pets. The logFav
function is called whenever the 'star' button is clicked next to a pet. It takes the id of the pet and button being clicked and checks to see if that id exists in our favorite_ids
map. If it does not exist, it is added and the button icon changes to a filled in star. If it does exist in the map, it is removed and the icon switched back to the empty star.
So that explains how we are tracking which pets are our favorites, but how do we make that second call to only pull them?
Here's how.
We add an event handler to this button that first sets div holding our favorite pets to empty. It then goes through our favorite_ids
map and makes a pet.get
API call for each id, requesting that pet's information. Within the callback function for each call, we request a separate function to display that pet in our favorites section.
Note: The above 'Grab Favorites' button has the id of #getFavs
.