4 Ways to Make an API Call in JavaScript
At some point in your developer journey, you will hear the acronym API. What is it exactly? I'm here to show you what it is and how you can integrate it into your JavaScript projects to create a robust application.
Knowing how APIs work and their different methods is foundational knowledge for web developers and can impress your peers with the APIs you create. Let's look deeper into ways you can make API requests in JavaScript.
An API (Application Programming Interface) allows different software to communicate with each other. In the context of web development, making an API call in JavaScript means requesting data from or sending data to a server. This interaction is essential for dynamic web applications where data is fetched asynchronously without needing to reload the entire page.
It's simply you, asking for some data from a server, and then it shows it to you on the platform where you made your request. In our context that would be our web browser. One of the best examples I've heard to explain this concept is the restaurant example.
You are the user making an order for some food. Your waiter or waitress is the API taking that request and getting it from the kitchen in the back, which would be the server.
For some examples of real-world APIs check out RapidAPI. There people create APIs for users to use and develop to make amazing applications and by the end of this article, you can start creating and selling your APIs also!
The Fetch API provides a modern way to make HTTP requests in JavaScript. It returns promises and is supported by most modern browsers.
const url = 'https://api.example.com/data';
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Here's an example using the Fetch API. The fetch
function initiates the API call, and the subsequent .then()
methods handle the response and potential errors.
Before the Fetch API, XMLHttpRequest was the go-to object for making asynchronous requests in plain JavaScript. It might seem a bit outdated, but it's still widely used and supported by all browsers.
const request = new XMLHttpRequest();
request.open('GET', 'https://api.example.com/data', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
const data = JSON.parse(this.response);
console.log(data);
} else {
console.error('Server returned an error');
}
};
request.onerror = function() {
console.error('Request failed');
};
request.send();
Axios is a popular JavaScript library that simplifies making HTTP requests. It's based on promises, making it cleaner and simpler than XMLHttpRequest.
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
jQuery, a widely-used JavaScript library, offers AJAX methods to make API calls. While not as modern as Fetch or Axios, it's still a reliable method, especially if you're already using jQuery in your project.
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.error('Error:', error);
}
});
Each method has its pros and cons. As always, it will completely depend on the project you are working on. In general though, if you are starting from scratch on a new project, then it's wiser to use Fetch or Axios because of promises. It's a very modern JavaScript paradigm that every developer should know by now and it's much easier to understand.
If you are working with legacy systems, chances are you are working with millions of lines of code that will depend on some jQuery or XMLHttpRequest API. In that case, it's much wiser to work with those instead to avoid break a large application.
Errors are a part of life, and its not any different with APIs. Handling errors properly can save you hundreds of hours of Googling if you know how to handle most cases. Promises have their catch methods, but sometimes you're going to need something more robust.
Wrapping any fetch requests or API calls in a try-catch block is good practice. It helps create these layers for error handling. JavaScript may not be the best at it, but it has improved over the years.
You are also going to need to know the error codes to help save time. Here is a list of them:
- 404: Not Found.
- 400: Bad Request.
- 401: Unauthroized.
- 403: Forbidden.
- 429: Too many requests.
- 500: Internal server error.
- Timeout Errors
- Parsing Errors
- Deprecation Warnings
Now there could be a very technical error that may not show up, but these are some basic ones that could easily be Googled. If you want to learn more about error codes, I'll leave a link to a great resource here.
Getting the data to the user fast and efficiently is an important aspect of User Experience (UX). There are many practices to help make it a better experience for many users. Here are some considerations you need to take a deeper look at to give your users the best UX:
- Response Time: See how long it takes for your API to respond. Slower response times can cause high bounce rates from your websites.
- Data Size: A bigger payload of data is harder to send through the network. It's good practice to only get the data you need to avoid slow downs from large payloads.
- Caching: Frequently accessed data can be cached to improve performance speed so browsers don't have to keep making specific requests.
- Concurrency: Make asynchronous calls to speed up your application. It gets painfully slow when you have to wait for each API call you make.
- Optimized Endpoints: Having your API endpoints have specific tasks and pull specific data can help a lot.
- Connection Handling: Learning how to reuse already established connections can significantly reduce overhead if done right.
- Error Handling: This goes without saying. If you catch your error efficiently, you can fix what needs to be done a lot quicker.
- Compression: Compressing the data to transfer is a common technique to help improve speed.
- Pagination: If you have a lot of data to display, pagination helps feed the user that data slowly.
Security is often overlooked when it comes to using APIs. This can obviously cause weak points in your systems if you're working with large companies. Be responsible and always follow security principles when workig with APIs. Here are some things to remember:
- Sensitive Data: Never expose API keys or sensitive data in client-side code.
- HTTPS: Always use HTTPS for API calls to encrypt data in transit.
- CORS: Understand Cross-Origin Resource Sharing to prevent unwanted cross-domain requests.
- Rate Limiting: Implement rate limiting to prevent abuse of your API endpoints.
- Input Validation: Always validate and sanitize your data sent to your API to prevent injections.
- Error Handling: Avoid revealing sensitive information in error messages.
- Authentication: Use strong authentication methods like OAuth.
- Authorization: Ensure users can only access data they are permitted to see.
- Logging: Maintain logs to monitor and audit API access.
- Updates: Regularly update your API libraries and dependencies to patch vulnerabiliies.
We're all guilty of making security an afterthought, but understanding and implementing these concepts can help distinguish a good dev from a great dev. You will definitely make some friends in your cybersecurity department as well.
All-in-all, APIs play a pivotal role in the functionality of dynamic web applications. Modern methods like the Fetch API and Axios have revolutionized the way we make API calls in JavaScript. However, traditional methods such as XMLHttpRequest and jQuery's AJAX remain relevant and widely used.
It's important to handle errors diligently and prioritize security when interacting with APIs. Moreover, staying on top of the latest methods and adhering to best practices ensures optimal performance and security. If you're using a web framework, look into any composables they provide out-of-the-box for handling API requests. This can dramatically improve development speed.
Now that you understand how APIs work in JavaScript, checkout my article Create a Simple Quiz App with HTML, CSS, and JavaScript to test out your new found knowledge or start a project of your own. Regardless, best of luck on your coding adventure.