Handling REST API Call in Angular

Hi Friends, This is Lakshman here.

Welcome back to the Series Angular Best Practices

Today, We will go through the best practices for handling REST API Call on App.

REST API Call

In our day-to-day development, we use REST API for below,

  • Fetch information.
  • Fetch information with Params.
  • Post Data for either Create / Update / Delete.

For each request, we required certain things to do.

  • API Url
  • HTTP Headers
    • Content Type either XML or JSON.
    • Authentication Token

In HTTP Header Content-Type & Authentication Token is common. So we required to store in Common Service to Set it.

It better to have a Function to generate Header with

  • ContentType
  • ContentType with Auth.

So we can access it.

The Function will look like below,

getHeader() {
     const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    return headers;
}

getHeaderAuth() {
     const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authentication': '<AuthKey>'
    });

    return headers;
}

In each request, if we need to pass params via two ways,

  • Query Params
  • Body

The Best Option via Body over Query Params, but Why

  • If Params contains URL or single quote or quotes, the request will fail.
  • If its body, we can encrypt & decrypt the content, where any other user won't see it.

If you have any doubts on Encrypt or Decrypt, Check this out

On-road head, we will discuss a lot of things.

Looking forward to your comments and share your feedback.

Until that, I am Lakshman, Signing Off.

Comments

Popular posts from this blog

Model Mapper in Angular

Implement Logging in Angular with Firebase

Dockerize Angular App for Dev