The Elearning Community • gestione API
Page 1 of 1

gestione API

Posted: Sat Feb 15, 2025 8:41 am
by megaservice
Buongiorno
sarebbe possibile avere un aiuto per la gestione delle chiamate API ?
Sono riuscito a creare il token di autenticazione , ma poi in qualunque achiamata lo passi
mi ritorna sempre lo stesso errore : version="1.0" encoding="UTF-8"?><XMLoutput><error>Autentication Token is not valid</error></XMLoutput>

questo invece è il risultato della creazione :
Autenticazione : true
Messaggio : You are authenticated.
Token : 799e0b57ac470b9668d3619f0902c575
Scadenza : 2025-02-15 07:52:07

Grazie

Re: gestione API

Posted: Sat Feb 15, 2025 8:49 am
by alfa24
Ciao,
Come passi il token alla chiamata successiva?
Scrivi un esempio please.

Re: gestione API

Posted: Sat Feb 15, 2025 10:51 am
by megaservice
Vediamo se riesco ad essere chiaro :
questo è un pezzo di codice che ottiene il token con successo :
Async Function Authenticate() As Task(Of Boolean)
Using client As New HttpClient()
Dim authUrl As String = FORMA_LMS_URL & API_AUTH_ENDPOINT

' Creazione dell'Authorization Header
Dim authCode As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(API_KEY & ":" & API_SECRET))
client.DefaultRequestHeaders.Add("X-Authorization", "FormaLMS " & authCode)
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"))

' Parametri della richiesta POST
Dim postData As New Dictionary(Of String, String) From {
{"username", "XXXXXXXXX"},
{"password", "XXXXXXXXXX"}
}
Dim content As New FormUrlEncodedContent(postData)

' Effettua la richiesta
Dim response As HttpResponseMessage = Await client.PostAsync(authUrl, content)
Dim responseText As String = Await response.Content.ReadAsStringAsync()

' Analizza la risposta XML
Dim xmlDoc As XDocument = XDocument.Parse(responseText)
Dim success As String = xmlDoc.Root.Element("success").Value

If success.ToLower() = "true" Then
token = xmlDoc.Root.Element("token").Value
Return True
Else
Console.WriteLine("❌ Errore nell'autenticazione: " & xmlDoc.Root.Element("message").Value)
Return False
End If
End Using
End Function

mentre questa è una chiamata ( lista utenti ) api

Async Function GetUserList() As Task(Of String)
Using client As New HttpClient()
Dim listUserUrl As String = FORMA_LMS_URL & API_LISTUSER_ENDPOINT

' Verifica che il token sia disponibile
If String.IsNullOrEmpty(token) Then
Return "❌ Errore: Token non disponibile. Effettua prima l'autenticazione."
End If

' Imposta l'header di autenticazione con il token
client.DefaultRequestHeaders.Add("X-Authorization", "FormaLMS " & token)
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"))

' Effettua la richiesta HTTP GET
Dim response As HttpResponseMessage = Await client.GetAsync(listUserUrl)
Return Await response.Content.ReadAsStringAsync()
End Using
End Function

dove API_LISTUSER_ENDPOINT è : "/api/user/userslist"
e FORMA_LMS_URL è : https://elearning.miosito.xxx/
prima ottengo il token e subito dopo faccio la chiamata , ma ottengo sempre :
<?xml version="1.0" encoding="UTF-8"?><XMLoutput><error>Autentication Token is not valid</error></XMLoutput>


Grazie

Re: gestione API

Posted: Sat Feb 15, 2025 12:36 pm
by alfa24
Mi spiace ma non posso aiutarti in ambiente "nemico".
Poi l'impaginazione non aiuta...

Re: gestione API

Posted: Mon Feb 17, 2025 7:50 am
by megaservice
Ah ah ah ...
ok . Puoi aiutarmi in ambiente "amico" con qualche esempio ?
diciamo che deve fare un piccolo script per avere la lista degli utenti.
Anche "Python" è ambiane nemico ?
Grazie

Re: gestione API

Posted: Mon Feb 17, 2025 9:32 am
by alfa24
Io ti consiglio di farti prima di tutto una classetta che gestisca le call, chiamiamola RestApiClass.
Quindi ti istanzi una

ApiCall = nuova istanza di RestApiClass

La tua classe conterrà chiaramente un metodo (chiamiamolo call) che gestisca le chiamate. Quindi per esempio quella per autenticazione:

ApiCall->call('auth/authenticate', {username: "username", password: "password"}, base_url, api_key, secret_key)

Nella risposta ci sarà il tuo token, da utilizzare in una chiamata successiva.

Ad esempio, se devi chiedere la lista utenti:

ApiCall->call('(user/userslist', {auth: TOKEN}, base_url, api_key, secret_key)


enjoy:)

Re: gestione API

Posted: Mon Feb 17, 2025 1:20 pm
by megaservice
GRazie . Interessante .
Ma secondo il tuo esempio anche se ho ottenuto il token , devo passare alla chiamata la KEY e la SECRET ?

Re: gestione API

Posted: Mon Feb 17, 2025 1:31 pm
by alfa24
Dipende da come istanzi la classe.
Siccome devi sempre allegare un header x-auth alla chiamata, e siccome quest'header deve essere un base64 della coppia key:sha1(param1,param2,param3, ..., secret_key), direi di si.

Re: gestione API

Posted: Tue Feb 18, 2025 7:49 am
by megaservice
Grazie per i tuoi consigli.
Momentaneamente ho risolto utilizzanso il codice univoco, poi in seguito cercherò di capire
come funziona il token.
Grazie ancora