logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Creating a Promise-Based API Request Function

author
Generated by
Himadhar Narayan

14/09/2024

JavaScript

Sign in to read full article

When it comes to working with APIs in JavaScript, understanding how to manage requests asynchronously is crucial. Asynchronous operations help improve application performance and user experience by allowing code execution to continue while waiting for responses. Promises are a key feature in JavaScript for handling these operations elegantly.

Today, we'll learn how to create a promise-based function to make API requests using the Fetch API. Let's get started!

Understanding the Fetch API

The Fetch API is modern and widely used for making network requests in JavaScript. It returns a Promise that resolves to the Response object representing the response to the request.

Why Use Promises?

Promises provide a cleaner way to handle asynchronous code compared to traditional callback functions. They allow you to chain .then() methods for success and .catch() methods for handling errors, making your code more readable.

Building Our Function

We will create a function called apiRequest that can handle GET and POST requests. This function will take care of sending the request to the specified URL and processing the response.

Here’s a simple example of how we can structure our apiRequest function:

function apiRequest(url, method = 'GET', data = null) { const options = { method: method, }; // If there is data to send (in case of POST requests), stringify it if (data) { options.headers = { 'Content-Type': 'application/json' }; options.body = JSON.stringify(data); } // Return the fetch promise return fetch(url, options) .then(response => { // Check if the response is okay (status in the range 200-299) if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } // Parse the response body as JSON return response.json(); }); }

How It Works

  1. Function Parameters: The apiRequest function takes three parameters:

    • url (string): The URL to which the request is sent.
    • method (string): The HTTP method to use (GET, POST, etc.), with a default value of 'GET'.
    • data (object): An optional payload for POST requests.
  2. Fetch Options: We create an options object to define the request method and any headers. If data is provided, we set the Content-Type header to application/json and convert our data object to a JSON string.

  3. Making the Request: The fetch function is called with the URL and options. It returns a Promise.

  4. Handling the Response: Inside the first .then(), we check if the response is OK (status code 200-299). If not, we throw an error. If it is okay, we parse the response as JSON and return it.

Example Usage

Now, let’s see how we can use our apiRequest function to fetch data from a sample API. We will use the JSONPlaceholder API, which is a great tool for testing.

// Example of a GET request apiRequest('https://jsonplaceholder.typicode.com/posts') .then(data => { console.log('GET Response Data:', data); }) .catch(error => { console.error('Error:', error); }); // Example of a POST request const newPost = { title: 'foo', body: 'bar', userId: 1, }; apiRequest('https://jsonplaceholder.typicode.com/posts', 'POST', newPost) .then(data => { console.log('POST Response Data:', data); }) .catch(error => { console.error('Error:', error); });

In Conclusion

With the promise-based apiRequest function implemented, we can now easily handle both GET and POST requests. The function is versatile and makes our code much cleaner and easier to maintain. The ability to chain promises allows us to manage asynchronous responses without the dreaded callback hell.

Popular Tags

JavaScriptAPIFetchAPI

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

Related Articles

  • Creating a Promise-Based API Request Function

    14/09/2024 | VanillaJS

  • JavaScript Debouncing and Throttling

    22/10/2024 | VanillaJS

  • Build a Deep Clone Utility for Objects in JavaScript

    14/09/2024 | VanillaJS

  • Exploring Micro tasks vs Macro tasks in JavaScript

    25/07/2024 | VanillaJS

  • Traverse JSON object to find paths leading to leaf nodes

    12/09/2024 | VanillaJS

  • Understanding JavaScript Event Delegation

    22/10/2024 | VanillaJS

  • Understanding JavaScript WeakMap and WeakSet

    22/10/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design