Friday, July 14, 2023

API Calling Post Method Most Common Error - misused header name 'authorization' business central

 Hello Friend

You must face below error while you try to call API post method with mullitple header value

misused header name 'authorization' business centra
















This error come because of invalid content type handle in API call

Below example you can see where we need to pass 2 header value


















BC Working Code:

           action("Chat GTP")
            {
                ApplicationArea = Suite;
                Caption = 'Chat GTP';
                Image = Production;
                Promoted = true;
                PromotedCategory = Process;
                PromotedIsBig = true;
                PromotedOnly = true;

                trigger OnAction()
                var
                    myInt: Integer;
                    Gpt_JsonObject_L: JsonObject;
                    Gpt_JsonText_L: Text;
                    Content: HttpContent;
                    Client: HttpClient;
                    Headers: HttpHeaders;
                    Request: HttpRequestMessage;
                    Response: HttpResponseMessage;
                    JSONResponse: Text;
                    JObject: JsonObject;
                begin

                    Gpt_JsonObject_L.Add('model', 'text-davinci-003');
                    Gpt_JsonObject_L.Add('prompt', 'how are you?');
                    Gpt_JsonObject_L.Add('temperature', 0.2);
                    Gpt_JsonObject_L.WriteTo(Gpt_JsonText_L);

                    Request.Method := 'POST';
                    Request.SetRequestUri('https://api.openai.com/v1/completions');

                    Headers.Clear();
                    Request.GetHeaders(Headers);
                    Headers.Add('Authorization', 'Bearer ' + 'sk-FxpqNnCvf1qTbz0m1EXGT
3BlbkFJ6B7V3oIcHHKnjs1N4c6O');
                    Content.WriteFrom(Gpt_JsonText_L);

                    Content.GetHeaders(Headers);
                    Headers.Remove('Content-Type');
                    Headers.Add('Content-Type', 'application/json');
                    Request.Content := Content;

                    if not Client.Send(Request, Response) then
                        Error('API Authorization token request failed...');

                    JSONResponse := '';
                    Response.Content().ReadAs(JSONResponse);

                    if not JObject.ReadFrom(JSONResponse) then
                        Error('Invalid response, expected a JSON object');

                    Message(JSONResponse);

                end;

Response will show in msg




















To lear more watch this video:

https://www.youtube.com/watch?v=QmCXUm0bEfU

I hope this help someone

Thank you for reading.

Keep Sharing....Keep Growing....

No comments:

Post a Comment