Web APIs are methods or interfaces exposed by the browser to perform certain tasks. Fetch is a Web API that lets you call RESTful or GraphQL APIs without needing to install any third-party module.
In this piece, we will learn how to send the request body along a POST request using fetch. So without any further ado, let’s jump in!
The fetch API lets you talk with other REST APIs. It is an asynchronous web API that comes with native JavaScript and returns the data in the form of promises. Unlike other HTTP packages, you do not install it via npm or yarn, and you can also use it to call any backend service.
Let’s break it down in steps to make things simpler and easy to follow:
Let’s find an API first that we can use to learn how to send the request body with fetch. For this purpose, we can use RapidAPI Hub, which houses over 35,000+ usable APIs.
We will use TextAPI, so please go ahead and subscribe to it.
Create a directory and open it in your preferred code editor. Now create an HTML file and write a basic boilerplate inside it.
html
<!DOCTYPE html><html lang="en"><head><title>Learn how to send request body using fetch</title></head><body><script></script></body></html>
We can write JavaScript inside the script tag. So, let’s create an object called options. This object will hold keys like method
, headers
, and body
. The body
key is the request body we will send to the server along with the API request.
html
<script>const options = {method: "HTTP METHOD",headers: {// http headers if there are any},body: "Add request body here"}</script>
Let’s add our API details in this options
object.
html
<script>const options = {method: 'POST',url: 'https://textapis.p.rapidapi.com/text',headers: {'Content-Type': 'application/json','X-RapidAPI-Key': '74cc79460fmsh3c6d0abcb93703cp140eb4jsn8975796733b1','X-RapidAPI-Host': 'textapis.p.rapidapi.com',},body: '{"url":"https://www.theguardian.com/world/2020/oct/24/thousands-join-poland-protests-against-strict-abortion-laws"}'};</script>
The last step is to call the API. Here is how you can do it:
html
<script>const options = {method: 'POST',url: 'https://textapis.p.rapidapi.com/text',headers: {'Content-Type': 'application/json','X-RapidAPI-Key': '74cc79460fmsh3c6d0abcb93703cp140eb4jsn8975796733b1','X-RapidAPI-Host': 'textapis.p.rapidapi.com',},body: '{"url":"https://www.theguardian.com/world/2020/oct/24/thousands-join-poland-protests-against-strict-abortion-laws"}',};fetch('https://textapis.p.rapidapi.com/text', options).then(response => response.json()).then(response => console.log(response)).catch(err => console.error(err));</script>
You can see that I have called the fetch API and provided it options object as a second parameter. Afterward, I called the API and logged the response on the console after converting it to JSON.
That’s all, folks! If you want to learn more about fetch, I recommend you read this piece. It has everything you need to start with fetch
to call APIs.