Prayag
Prayag

Reputation: 101

REST API call state maintained

I am using two REST API from HTML client.

  1. First REST API call for authentication
  2. Second REST API call for getdata

In chrome Advance REST CLIENT it will works without any issue. But when i call these two api from HTML ajax call second getdata api will not give me data.

As per my understaning using ajax call every time it has new call so state is not maintain between two call.

So how i can use this rest api from my web client?

my code:

    //DO AUTHENTICATION for all other API

    $.ajax({
    url: 'https://example.com/AuthorizationCheck.svc/AuthorizationCheck?Credentials=xyz',

    success: function (data) {
        json = data;

        debugger;
    },
    error: function (data) {
        debugger;
    },

});

        //GET API
        $.ajax({
        type: "GET",
        url: 'https://example.com/test.svc/Getdata?searchterm=abc',
        success: function (data) {
        //RETURN NULL AS AUTHENTICATION REQUIRED
            debugger;
        },
        error: function (data) {
            debugger;
        },

    });

Upvotes: 0

Views: 99

Answers (2)

Ran Hassid
Ran Hassid

Reputation: 2788

You need to pass your credentials also in the getData call since Rest API is stateless which means that you have a new state in each api call . in order to avoid entering the username and password in each call you can override the onBeforeSend event and there encode your username and password in order to do it please refer do the following:

beforeSend: function (request) {
request.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password)); }

more info can be found here:

http://api.jquery.com/jquery.ajax/

Upvotes: 1

Ran Hassid
Ran Hassid

Reputation: 2788

it really depends which authentication mechanism you are using. if you use basic authentication then you need to send user name and password in every request (you can also base64 encode them and send them in the request header) if you use oAuth/Api key then you need to send the generated token in the request

It will be very helpful to get more info about what kind of API you are trying to consume.

Upvotes: 0

Related Questions