DEV Community

Busari Ridwan
Busari Ridwan

Posted on

2

Using ChatGPT: Examples of POST and GET API Call in JavaScript

Netizens have been talking about ChatGPT by OpenAPI and I decided to try it out. My search goes thus - "Example of get and post call in JavaScript" and below is the response I got.

In JavaScript, you can use the fetch() API to make HTTP requests, such as GET and POST requests. Here's an example of a GET request:

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

Enter fullscreen mode Exit fullscreen mode

This code uses the fetch() method to make a GET request to the specified URL. The .then() method is used to handle the response returned by the server. The first .then() method is used to parse the response as JSON, and the second .then() method is used to access the data and do something with it.

For a POST request, you can use the fetch() method along with the Request() constructor to specify the request method and the request body:

const data = { title: "foo", body: "bar", userId: 1 };

fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

Enter fullscreen mode Exit fullscreen mode

This code creates a JavaScript object that represents the data to be sent to the server, and then it uses the fetch() method to make a POST request to the specified URL. The headers option is used to set the Content-Type header to application/json, and the body option is used to send the data as the request body.

Please note that these are examples only and the URLs are not real endpoints, that means that you will not get a real response from these URLs.
Also, in a real-world scenario, you should also handle errors and other edge cases, and add validations, loading spinners, and other features.

What's your thought on ChatGPT?

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more