Search code examples
excelvba

How to get the token to be used later in API REST


I need to upload files in a server, that requires a login to get a token to be used when I upload.

To login, I adapted How do we use restful APIs from Excel macros (vba)?

Sub LOGIN()

    Dim Request As Object
    Dim authKey As String
    Dim stUrl As String
    Dim response As String
    Dim requestBody As String
    
    stUrl = "https://WEB/oauth/connect/token?grant_type=client_credentials"

    Set Request = CreateObject("MSXML2.XMLHTTP")
    
    requestBody = "{ ""client_id"": ""USERNAME"", " & """client_secret"": ""PASSWORD""}"
        
    With Request
        .Open "POST", stUrl, False
        .setRequestHeader "Content-type", "application/json"
        .send (requestBody)
        response = .responseText
    End With

    MsgBox responseText

I need to know the token to upload the files, but responseText is blank. If I try to save it in an Excel cell, it is also blank.

In a CMD screen with

curl -X POST -H "client_id:USERNAME" -u USERNAME:PASSWORD "https://WEB/oauth/token" -d "grant_type=client_credentials"

I don't receive any error, but also not any information.

How can I get the token response and save it in a variable in VBA?

This is the web: https://api.valenciaportpcs.net/messaging/swagger/index.html


Solution

  • Try this;

    ......
    ....
        XMLHTTP.send body
        
        If XMLHTTP.Status = 200 Then
            response = XMLHTTP.responseText
            
            Dim myToken As String
            myToken = Replace(Split(Split(response, ":")(1), ",")(0), """", "")
            
            MsgBox myToken
        Else
            MsgBox XMLHTTP.statusText
        End If