When building an application, you'll often need to retrieve or send data to an API (Application Programming Interface). Making API calls allows your app to leverage functionality and data from other services. This guide covers the basics of making API requests in your code.
API Request Anatomy
An API request typically contains:
Here is an example GET request:
GET https://api.example.com/v1/users
Authorization: Bearer abc123
And a POST request:
POST https://api.example.com/v1/users
Authorization: Bearer abc123
{
"name": "John Doe",
"email": "[email protected]"
}
Making API Calls
There are a few common ways to make API requests:
1. Fetch API
The Fetch API allows you to make requests and handle responses easily:
fetch('https://api.example.com/v1/users', {
method: 'POST',
headers: {
'Authorization': 'Bearer abc123'
}
})
.then(response => response.json())
.then(data => console.log(data))
2. Axios
Axios is a popular HTTP client library for making API calls:
axios.post('https://api.example.com/v1/users', {
name: 'John Doe',
email: '[email protected]'
}, {
headers: {
'Authorization': 'Bearer abc123'
}
})
.then(response => {
console.log(response.data)
})
3. Wrappers & SDKs
Many APIs have client libraries or SDKs (Software Development Kits) to abstract away the underlying HTTP requests and provide convenience methods for accessing the API. These make development quicker and easier.
Tips
Making successful API calls does take some learning, but gets much easier with examples and practice!