Jason Shoulders
Jason Shoulders

Reputation: 659

API token unauthorized

On line

Dim responseBody = client.DownloadString(searchUrl) 

I am getting an 401 unauthorized error. I read the API @ https://api.speechanddebate.org and used the sessions function to get a token using my login and password. If I access the page directly using a browser, it successfully returns the data.

I'm either not setting up something correctly or the API is lying that I can access this programmatically. Any ideas?

Public Function GetSchoolIdByName(schoolName As String, schoolState As String, token As String) As String
        Dim searchUrl As String = $"https://api.speechanddebate.org/v2/search?q={HttpUtility.UrlEncode(schoolName)}&type=schools"

        Try
            Using client As New WebClient()
                'client.Headers(HttpRequestHeader.Authorization) = "Bearer " & token
                client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " & token)

                Dim responseBody = client.DownloadString(searchUrl)

                Dim root As JsonElement = JsonDocument.Parse(responseBody).RootElement

                If root.ValueKind = JsonValueKind.Array Then
                    For Each student As JsonElement In root.EnumerateArray() ' Iterate through the array elements
                        Dim name As String = student.GetProperty("name").GetString()
                        Dim school As String = student.GetProperty("school").GetString()
                    Next
                End If

                'Return studentRankings

            End Using

        Catch ex As WebException
            Console.WriteLine($"Web Request Error: {ex.Message}")
            Return Nothing
        Catch ex As Exception
            Console.WriteLine($"An error occurred: {ex.Message}")
            Return Nothing
        End Try

    End Function

Upvotes: 0

Views: 34

Answers (1)

Jason Shoulders
Jason Shoulders

Reputation: 659

The admin of the API responded with this information and when I added the code below, it finally fixed it.

"You have to base64 encode the Authorization header.

Authorization: Basic 1231009:token should actually be:

Authorization: Basic .

That is, you base64 encode the string "<nsda_id>:" first."

Public Function GetBase64EncodedCredentials(nsdaId As String, token As String) As String
    Dim credentials As String = nsdaId & ":" & token
    Dim credentialsBytes As Byte() = Encoding.UTF8.GetBytes(credentials)
    Dim base64Credentials As String = Convert.ToBase64String(credentialsBytes)
    Return base64Credentials
End Function

Upvotes: 0

Related Questions