kawnah
kawnah

Reputation: 3424

How to pass an access token in an ajax call

I asked a question earlier today about making an ajax call with the ZenDesk API.

I can successfully run the following in command prompt and create a ticket in ZenDesk (my_api_token is the API token string):

curl https://mydomain.zendesk.com/api/v2/tickets.json \
  -d '{"ticket": {"subject": "Test ticket from API", "comment": { "body": "Just a test -kawnah" }}}' \
  -H "Content-Type: application/json" -u kawnah@email.com/token:my_api_token -X POST

What I'm trying to understand now is how this translates into an ajax call. This is the documentation I'm following.

What I am doing at the moment is below:

$.ajax({
        type: 'post',
        url: 'https://domain.zendesk.com/api/v2/tickets.json',
        data: {
          "ticket": {
            "subject": "new contact from " + $('#contactFormEmail').val(),
            "comment": {
              "body": $('#contactFormMessage').val()
            }
          }
        },
        // ==========================================================
        // This is where I'm confused....
        // How do I authorize the API via the token? It's here right?
        // I'm trying it via standard setRequestHeader Authorization
        // For learning purposes in my local copy I'm pasting the key 
        // straight in, just to get it working.
        // I know this is bad practice. 
        // ==========================================================
        beforeSend : function( xhr ) {
            xhr.setRequestHeader( 'Authorization', 'BEARER my_api_token' );
        },
        success: function( response ) {
            console.log(response);
        },
        error : function(error) {
            console.log(error);
        }
      });

Here are some answers and docs I've looked at already but I'm still really confused:

(best one): https://auth0.com/blog/using-json-web-tokens-as-api-keys/

The definitive guide to form-based website authentication

Grafana passing access token in url

https://developer.zendesk.com/rest_api/docs/core/tickets#create-ticket

What should I be doing differently?

Upvotes: 3

Views: 7323

Answers (2)

kawnah
kawnah

Reputation: 3424

The accepted answer is what I needed, but there is a big distinction that I was missing. If others read this I figured it might help.

I was trying to use the api token, when what I really needed was the api key.

Upvotes: 1

Qaiser Mehmood
Qaiser Mehmood

Reputation: 212

Code ok, but you need to generate api key using following URL.

https://developer.zendesk.com/requests/new

On above URL give address of your api URL and grant access. It will work for you.

Upvotes: 1

Related Questions