In this section, we will explore how to work with APIs in TypeScript. APIs (Application Programming Interfaces) allow different software systems to communicate with each other. We will cover the following topics:
- Introduction to APIs
- Making HTTP Requests
- Handling API Responses
- Error Handling in API Calls
- Practical Example: Fetching Data from a Public API
- Exercises
- Introduction to APIs
APIs are a set of rules and protocols for building and interacting with software applications. They define the methods and data formats that applications can use to communicate with each other. In web development, APIs are often used to fetch data from a server or send data to a server.
- Making HTTP Requests
To make HTTP requests in TypeScript, we can use the fetch
API, which is a modern and widely supported way to make network requests. Here is a basic example of how to use the fetch
API:
// Making a GET request to a public API fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.error('Error fetching data:', error); });
Explanation:
fetch('https://api.example.com/data')
: Initiates a GET request to the specified URL..then(response => response.json())
: Converts the response to JSON format..then(data => { console.log(data); })
: Logs the fetched data to the console..catch(error => { console.error('Error fetching data:', error); })
: Catches and logs any errors that occur during the request.
- Handling API Responses
When working with APIs, it's important to handle the responses properly. This includes checking the status of the response and parsing the data correctly. Here is an example:
fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('Error fetching data:', error); });
Explanation:
if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); }
: Checks if the response status is not OK (i.e., not in the range 200-299) and throws an error if it's not.
- Error Handling in API Calls
Proper error handling is crucial when working with APIs. You need to handle both network errors and application-specific errors. Here is an example of how to handle different types of errors:
fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { if (error.name === 'TypeError') { console.error('There was a problem with the fetch operation:', error); } else { console.error('Error fetching data:', error); } });
Explanation:
if (error.name === 'TypeError') { console.error('There was a problem with the fetch operation:', error); }
: Checks if the error is aTypeError
(which usually indicates a network error) and logs a specific message.
- Practical Example: Fetching Data from a Public API
Let's put everything together in a practical example. We will fetch data from a public API and display it in the console.
Example: Fetching User Data from JSONPlaceholder
interface User { id: number; name: string; username: string; email: string; } fetch('https://jsonplaceholder.typicode.com/users') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then((data: User[]) => { data.forEach(user => { console.log(`ID: ${user.id}, Name: ${user.name}, Username: ${user.username}, Email: ${user.email}`); }); }) .catch(error => { console.error('Error fetching data:', error); });
Explanation:
interface User { ... }
: Defines a TypeScript interface for the user data.fetch('https://jsonplaceholder.typicode.com/users')
: Fetches user data from the JSONPlaceholder API..then((data: User[]) => { ... })
: Specifies that the data is an array ofUser
objects and logs each user's details to the console.
- Exercises
Exercise 1: Fetching Posts from JSONPlaceholder
Task: Write a TypeScript function that fetches posts from the JSONPlaceholder API and logs the title and body of each post.
Solution:
interface Post { id: number; title: string; body: string; } function fetchPosts() { fetch('https://jsonplaceholder.typicode.com/posts') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then((data: Post[]) => { data.forEach(post => { console.log(`Title: ${post.title}, Body: ${post.body}`); }); }) .catch(error => { console.error('Error fetching posts:', error); }); } fetchPosts();
Exercise 2: Handling Errors
Task: Modify the fetchPosts
function to handle network errors and log a specific message for TypeError
.
Solution:
function fetchPosts() { fetch('https://jsonplaceholder.typicode.com/posts') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then((data: Post[]) => { data.forEach(post => { console.log(`Title: ${post.title}, Body: ${post.body}`); }); }) .catch(error => { if (error.name === 'TypeError') { console.error('There was a problem with the fetch operation:', error); } else { console.error('Error fetching posts:', error); } }); } fetchPosts();
Conclusion
In this section, we learned how to work with APIs in TypeScript. We covered making HTTP requests using the fetch
API, handling API responses, and error handling. We also implemented a practical example of fetching data from a public API and provided exercises to reinforce the concepts. In the next section, we will delve into error handling in more detail.
TypeScript Course
Module 1: Introduction to TypeScript
- What is TypeScript?
- Setting Up the TypeScript Environment
- Basic Types
- Type Annotations
- Compiling TypeScript
Module 2: Working with Types
Module 3: Advanced Types
Module 4: Functions and Modules
Module 5: Asynchronous Programming
Module 6: Tooling and Best Practices
- Linting and Formatting
- Testing TypeScript Code
- TypeScript with Webpack
- TypeScript with React
- Best Practices