W03 Learning Activity: Third-Party APIs
Overview
At this point in your own development hopefully you have realized that developers do not need to write everything themselves. You have seen that browser tools continue to evolve and provide access to built-in tools that enable useful application solutions through abstraction. Third-Party APIs are another way to leverage the work of others to build your own applications. Third-Party APIs are interfaces provided by external services that allow developers to access their functionality and data. These APIs can be used to integrate features such as payment processing, social media sharing, and data retrieval into your own applications.
Abstraction is the process of removing or suppressing details to focus on the main idea. In programming, abstraction is a way to reduce complexity and increase efficiency by hiding unnecessary details and showing only the essential features of an object or system like working through an interface, an Application Programming Interface or API.
Prepare
To prepare to consume third-party APIs, you should understand the following concepts:
- API Endpoints: The specific URLs where the API can be accessed.
- HTTP Methods: The methods used to interact with the API, such as GET, POST, PUT, and DELETE.
- Authentication: The process of verifying the identity of the user or application making the request.
- Response Formats: The format in which the API returns data, such as JSON or XML.
- Error Handling: How to handle errors that may occur when making requests to the API.
Here is an example API that supports these concepts:
https://jsonplaceholder.typicode.com/posts
This free, mock API services simulates a real-world API and is commonly used for testing and prototyping
purposes. The resources available on jsonplaceholder include posts (100 records), comments (500), albums (100),
photos (5000), todos (200), and users (10). Each resource has its own set of endpoints and supports the same HTTP
methods. These resources have relationships, for example, albums have photos, and posts have comments. For
example, the /posts
endpoint freely allows you to create, read, update, and delete posts.
This API uses the following HTTP methods:
- GET: Retrieve a list of posts or a specific post.
Example endpoint:GET /posts
retrieves all posts, whileGET /posts/{id}
retrieves a specific post by ID. - POST: Create a new post.
Example:POST /posts
creates a new post with the provided data in the request body. - PUT: Update an existing post.
Example:PUT /posts/{id}
updates an existing post by ID with the provided data in the request body. - DELETE: Delete a post.
Example:DELETE /posts/{id}
deletes a specific post by ID.
Here is an example using the default GET
method
const todo = document.getElementById('todo-output');
async function getTodo() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/77');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const json = await response.json();
todo.textContent = json;
} catch (error) {
console.error('There was a problem fetching the data:', error);
}
}
todo.textContent = 'Loading...';
getTodo();
This code uses the Fetch API to make a GET
request to the /todos/77
endpoint of the
JSONPlaceholder
API. It retrieves a single todo item with ID 77 and displays that object as displayed below.
If there is an error, it logs the error message to the console.
jsonplaceholder data from example
jsonplaceholder.typicode.com does not require authentication as a basic, free service for prototyping. Most APIs require some form of authentication to ensure that only authorized users can access the API and its resources. Authentication can be done using an API key, OAuth, or other methods. The specific authentication method used by an API will depend on the API provider and the level of security required for the API.
For more information on this API, you can refer to the JSONPlaceholder documentation.
Activity Instructions
In this activity, use the jsonplaceholder.typicode.com mock API service to return the all the users and display them on the screen in an unordered list.
Use the following requirements to complete the activity:
- Use the
async/await
approach to Fetch the API and make a GET request to the/users
endpoint of the JSONPlaceholder API. - Retrieve all the user records from the response data.
- Display individual user records as list items
li
displaying the 'name' and 'email' of each user. - Handle any errors that may occur during the request.
Check Your Understanding – Example Solution
CodePen: Consuming a Mock API Service