Al code - POST to rest API

terry823terry823 Member Posts: 4
Hello,
I'm having trouble doing a post call to rest api. I've been able to successfully post using postman tool to confirm the API's working fine. I've also tried to use "Arend-Jan Kauffmann" github example kauffmann.nl/2017/07/18/al-web-service-examples/ but to it's not working in my case.

I need to post to get authentication token which would be sent over with subsequent requests until it expires. here is an example of what needs to happen:
url: https://testapi.com/gettoken
content-type:'applicaiton/application/x-www-form-urlencoded'
authorization:'Basic "base64secretkey"'

the above two are part of heard. Now I need to supply request content. In postman I add this to body raw:
scope=service&grant_type=client_credentials

In AL code I use httpclient:
gHttpClient.DefaultRequestHeaders.Add('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
gHttpClient.DefaultRequestHeaders.Add('authorization', 'Basic ' + lbase64key);

I have a httpcontent which I'm adding the content that needs to go in the request body then I assign this value to request content directly. I'm not sure if this is the right way of doing this part. I don't see an "Add content" method/property for request.
ghttpcontent:HttpContent;
greqMsg:HttpRequestMessage;
gresMsg:HttpResponseMessage;

ghttpcontent.Writefrom('scope=service&grant_type=client_credentials');

greqMsg.SetRequestUri(url);
greqMsg.Method := 'Post';
greqMsg.Content := gcontent;

ghttpclient.send(greqMsg,gresMsg);

I run into two issues here:

1: I get misused headers error with the content-type I defined on the httpclient.
2: When I remove this header for content-type from httpclient I get 400 code by checking the response code and result.


It would really help if someone can point me in the right direction. I've been at this for days now. By the way I've tested the get and it works.

Thanks!


Best Answer

  • terry823terry823 Member Posts: 4
    Answer ✓
    Thought I update this the problem have been resolved you can see the solution here. This is so it helps anyone else in a pickle.

    AL the best :tongue:

Answers

  • terry823terry823 Member Posts: 4
    Answer ✓
    Thought I update this the problem have been resolved you can see the solution here. This is so it helps anyone else in a pickle.

    AL the best :tongue:
  • prakaash786prakaash786 Member Posts: 12
    Hi terry,

    I am also trying to access the access token for my app in azure and I have done lots of experiments but didn't work, I am not able to get the authorisation code using GET request. Can you please let me know how can I do that.

    I have failed trying HTTP Client, HTTP Request, AuthroizationCodeFlow, AuthenticationContext, Identity model and others (in separate attempts), It would be really helpful if you can help me.

    Regards,
    Chandra Prakash Soni
Sign In or Register to comment.