This tutorial aims to provide a detailed understanding of HTTP methods and how they are used in RESTful APIs. By the end of this tutorial, you will have a solid understanding of HTTP methods and their practical applications.
You will Learn:
Prerequisites:
HTTP stands for Hypertext Transfer Protocol. It is a protocol that facilitates communication between client and server in a network. HTTP methods define the type of request a client sends to a server. The primary HTTP methods include GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS.
GET: The GET method retrieves data from a server. It only fetches data and does not modify it.
POST: The POST method sends data to a server to create a new resource.
PUT: The PUT method updates an existing resource with new data.
DELETE: The DELETE method removes an existing resource.
PATCH: The PATCH method updates parts of an existing resource.
HEAD: The HEAD method retrieves the HTTP headers from a response, without the body.
OPTIONS: The OPTIONS method describes the communication options for the target resource.
GET method:
// Using the fetch API to make a GET request
fetch("https://api.example.com/items")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
POST method:
// Using the fetch API to make a POST request
let data = { name: "new item", price: "99.99" };
fetch("https://api.example.com/items", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
We have covered the basics of HTTP methods, their use in RESTful APIs, and provided some practical examples. The next step would be to dive deeper into each method and explore their nuances. You may also want to explore other aspects of HTTP, such as status codes and headers.
Exercise 1: Write a function that makes a GET request to "https://api.example.com/items" and logs the response to the console.
Exercise 2: Write a function that makes a POST request to "https://api.example.com/items" with a new item and logs the response to the console.
Solutions:
Solution 1:
function getItems() {
fetch("https://api.example.com/items")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
}
getItems();
We're making a GET request to the provided URL and then logging the response.
Solution 2:
function postItem() {
let data = { name: "new item", price: "99.99" };
fetch("https://api.example.com/items", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
}
postItem();
We're making a POST request with a new item to the provided URL and then logging the response.
For further practice, try to write functions for PUT, DELETE, PATCH requests.