DEV Community

Rafi
Rafi

Posted on

6 4

API request using tagged template literals

I recently came across this awesome video introducing tagged template literals. At the end of the video @kentcdodds does talk about possible use case with API request with something like this.

const response = await GET`https://dev.to`;
console.log(response.text())

So here it is a rudimentary implementation for that

function GET(literalStrings, ...interpolations) {
  const URL = literalStrings[0];
  let headers = {
    METHOD: "GET"
  };

  if (interpolations.length === 1) {
    headers = {...headers, ...JSON.parse(interpolations[0])};
  }

  return fetch(URL, headers);
}

you can use this as follows

const headers = JSON.stringify({
  cretentials: "include"
});

const response = await GET`https://dev.to ${headers}`;
console.log(response.text());

Similarly you can write POST, PUT and DELETE too (with third stringified argument as request body it if is present).

So why do you want something like this ?

  1. It might be easy to mock the fetch functions while testing by importing mock GET function (argument can be made against this)
  2. It is easier to test the request made since it is just a string
  3. It looks pretty

If the implementation was not dependent on fetch API it could be used in other environments like node (if you did not have node-fetch).

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site