DEV Community

Afroza Nowshin
Afroza Nowshin

Posted on

# in an API GET Request: How to Handle?

I just learned a new thing that I want to share with the world.

A computer is a dumb machine. Computer programs and codes are basically teaching a dumb sh** about something.

Consider a case where you need to send data with a special character in API - @, #, $, etc. For example, I had to make an API request where id has a # before it:

http://localhost:3000/#20000
Enter fullscreen mode Exit fullscreen mode

I learned the hard way that even though you can console the whole URL in any format you want. As soon as you pass the URL to an Axios or fetch API, the hash sign is auto-discarded.

What is the solution?

Pass the entire ID to the encodeURIComponent() function and use the encoded ID to your request URL.

const encodedId = encodeURIComponent(Id);

const apiUrlWithId = `http://someapi.com/${encodedId}`;
Enter fullscreen mode Exit fullscreen mode

That's it. Yeah, you have to encode the hash or the special character just to make the request properly.

Top comments (0)