What next after learning the basics of Javascript? Well, stay with me; I have got you covered. Ever heard of REST APIs? It's a powerful tool you have to add to your skills as a JS developer.
This article is about REST APIs and how to use them as a JavaScript developer.
Table of Content
- Who is this article for?
- Requirements?
- What is an API?
- REST APIs?
- How to Make Requests with Rest APIs
- HTTP Methods
- GET HTTP Method
- POST HTTP Method
- PUT HTTP Method
- DELETE HTTP Method
- Practical Example: Weather Web Application
- Conclusion
1. Who is this article for?
This article is tailor-made for JavaScript developers who are eager to take a step- further as a JavaScript developer. If you’re new to the concept of REST APIs or not sure about how they work, this is also for you.
2. Requirements?
Basic knowledge of JavaScript is enough to get you started. Sounds good?
To get started, let’s get acquainted with some definitions.
3. What is an API?
Think of API as the waiter that gets your order in a restaurant; the waiter serves as a bridge between you, the customer (who places an order), and the chef in the kitchen (who makes the food). The waiter acts as the API (Application Programming Interface), which is a communication channel between two applications. For example, a web form submits data to a database.
An API handles incoming web form requests and sends a response back.
4. REST APIs?
REST (Representational State Transfer) is a type of API that makes communication between two applications smooth and organized by following a set of rules.
5. How to Make Requests with Rest APIs
Let’s explore the following example, there is a common Rest API called jsonplaceholder which provides random user data. Using JavaScript fetch() API or async/await, let’s make a request
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(json => console.log(json))
Or you can use the async / await method:
async function GetData() {
let endPoint = "https://jsonplaceholder.typicode.com/users";
const request = await fetch(endPoint);
const response = await request.json();
console.log(response)
}
GetData() // call the function
You can check out this link to a beginner’s guide to Promise in JavaScript. If you’re not used to this code, https://www.freecodecamp.org/news/javascript-promises-for-beginners/
So, if you want to add data to some kind of database using an API, you are going to use the fetch API. However, this time, you will have to specify the methods you want to use.
Let’s explore some of those methods.
6. HTTP Methods
HTTP methods let the REST API know the type of request you want to make. The most common types are GET, DELETE, POST, and PUT, all known as CRUD operations (Create, Read, Update, Delete).
Let us explore the methods.
7. GET HTTP Method
This method is used to fetch information from the server. For a get request, the server searches for the data you requested and sends it back to you.
async function userData() {
let endPoint = "https://jsonplaceholder.typicode.com/users";
const request = await fetch(endPoint, {method: "GET"});
const response = await request.json();
console.log(response)
}
userData() // call the function
8. POST HTTP Method
POST Method is used to add data to REST API. body option is to pass the data to our API. However, this data is usually stored in JSON format, so we convert to the object to JSON with the JSON.stringify() method.
async function addData() {
let endPoint = "https://jsonplaceholder.typicode.com/users";
const request = await fetch(endPoint, {
method: "POST",
body: JSON.stringify(data)
});
const response = await request.json();
console.log(response);
}
const data = { firstName: "Jane Doe", age: 25 };
addData(); // call the function
9. PUT HTTP Method
This method update the data when working with REST API.
Let’s update user id 3
async function UpdateData() {
let endPoint = "https://jsonplaceholder.typicode.com/users/3";
const request = await fetch(endPoint, {
method: "PUT",
body: JSON.stringify(data)
});
const response = await request.json();
console.log(response);
}
const data = { age: 32 };
UpdateData(); // call the function
10. DELETE HTTP Method
This method allows you to delete user data from the server.
async function deleteData() {
let endPoint = "https://jsonplaceholder.typicode.com/users/10";
const request = await fetch(endPoint, { method: "DELETE" });
const response = await request.json();
console.log(response);
}
deleteData(); // call the function
11. Practical Example: Weather Web Application
Let’s build a weather web application. To get this started, we are going to use:
- To get the API key, you need to sign up with https://openweathermap.org/api
Let’s build the HTML and CSS of the web application.
- Create HTML file
<body>
<div class="container">
<div class="input">
<input type="text" class="inputValue" placeholder="Enter Location" />
<button class="button"><i class="fas fa-search"></i></button>
</div>
<div class="displayWeather">
<h1 class="temp">----°C</h1>
<p class="desc"></p>
</div>
</div>
</body>
- Create CSS file
*click this link to access the css file...
- Create JS file
Step 1: To get the API key, you need to sign up with https://openweathermap.org/api
const apiKey = "YOUR_API_KEY";
const apiUrl = "https://api.openweathermap.org/data/2.5/weather";
Step 2: Create variable for all HTML elements.
// Create variable for all HTML content
let button = document.querySelector(".button");
let inputvalue = document.querySelector(".inputValue");
let nameVal = document.querySelector(".name");
let temp = document.querySelector(".temp");
let desc = document.querySelector(".desc");
Step 3:
Add EventListener to the search button to fetch weather data for the entered city and display an alert message if you enter the wrong city.
// Add EventListener to the search button
button.addEventListener("click", function () {
// Fetch data from open weather API
fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${inputvalue.value}&units=metric&appid=108dd9a67c96f23039937fe6f3c91963`
)
.then((response) => response.json())
.then(displayData)
.catch((err) => alert("Wrong City name"));
});
Step 4:
Create a displayData function to display the weather on the HTML element.
// create Function to display weather on html document
const displayData = (weather) => {
temp.innerText = `${weather.main.temp}°C`;
desc.innerText = `${weather.weather[0].main}`;
};
Conclusion
Understanding REST APIs is so important for a JavaScript developer. This article has helped sharpen your understanding of REST APIs and how you can use them to build your own applications.
The weather app was gotten from medium Alwazkazi3
https://alwazkazi3.medium.com/creating-a-weather-app-using-api-javascript-4d7bb26bbc92
Top comments (0)