Data Formats and JSON
In order for our application to make a request to an API, the data will need to be formatted in a way both our application and the API can understand.
A data format is a set of rules that govern how data is written, organized, and labeled. Data formats make working with data consistent and reliable.
Let’s consider an API that serves information about the books in a library. In this example, we searched for “An Astronaut’s Guide to Life on Earth”.
The API returned a match for our search. The search provides us with information that may be useful to the user in the form of the title, author, ISBN, the year the book was published, the subjects of the book, and if the book is currently available for checkout.
JSON is a collection of key-value pairs. In the example above,
"title" is a key
and it’s value is
"An Astronaut's Guide to Life on Earth".
The key-value pairs describe the data that is being transferred.
A JSON key MUST be a string, but the value may be a number, string, boolean, array, object, or null.
In the example above, the JSON describes one object, a book! All of the keys are strings, and the values are: string, string, number, number, array, and boolean respectively.
JSON can also be used to describe a collection of objects at the same time. Consider we search for the word “Astronaut”.
This time, our search term “Astronaut” returned multiple books, and so a collection of book objects was returned in JSON format.
Each book object can be found in the array with the key
"book". Each book
contains the keys
When we make a request to an API, the API formats the data we requested into JSON and then responds to our request with the JSON representation of our request.
Check Your Understanding
What does API stand for?
Why might you connect to an API?
What purpose does JSON serve?