consumo de API REST con HMG

HMG en Español

Moderator: Rathinagiri

User avatar
nekbmm
Posts: 129
Joined: Sat Jul 16, 2016 3:16 am
DBs Used: DBF,SQLite
Location: Ivanjica, Serbia

Re: consumo de API REST con HMG

Post by nekbmm »

I do not know if it will work because I do not have authorization data, I have no way to check.
I found the Swagger UIhttps://rcrf.trezor.gov.rs/swagger/index.html and what surprised me is that there is a different json structure for the "/ api / invoice / register" function than that given in https://crf.trezor.gov.rs/docs/user/int ... ceregister

I think these are different versions of the API.

Thank you for your reply. I tried your example and hb_HGetDef() returns empty creationTime, accessToken and refreshToken even though they are
shown in response(attachment).

How can I access these data?
Attachments
odgovor.PNG
odgovor.PNG (9.79 KiB) Viewed 4342 times
edk
Posts: 999
Joined: Thu Oct 16, 2014 11:35 am
Location: Poland

Re: consumo de API REST con HMG

Post by edk »

nekbmm wrote: Sun Mar 21, 2021 7:36 pm How can I access these data?
Oh, I was expecting a different response (that's how it is, if I don't know Serbian :D )
The AccesToken is included in the "payload" key. First, the value of the "payload" key should be read, we should receive another Hash, and from this Hash we read the "accessToken" key.
Check out this code snippet:

Code: Select all

//login
cApiFunction :=  "/api/login"

//prepare json
hAtributi := { => }

hAtributi ["login"] := "foo"
hAtributi ["password"] := "bar"

strfile (hb_jsonEncode( hAtributi , .F. ), 'login_json.txt')

cResp := SendRestApi( cUrl + cApiFunction, hb_jsonEncode( hAtributi , .F. ), oRestApi )

IF cResp = "!ERROR!"
	MsgStop (cResp)
	oRestApi := Nil
	Quit
ENDIF

IF oRestApi:Status <> 200
	MsgStop ( "HTTP status: " + hb_NToS(oRestApi:status) + " "  +oRestApi:statusText + CRLF + CRLF + "Response: " + cResp )
ENDIF

hResp   := hb_jsonDecode( cResp )
hStatus := hb_HGetDef( hResp  , "status", { => } )

msginfo ("Message :" + hb_HGetDef( hStatus  , "message", "" ) + CRLF + "Code    :" + hb_ValToStr ( hb_HGetDef( hStatus  , "code", "" ) ) )

hPayload := hb_HGetDef( hResp  , "payload", { => } )

cCreationTime := hb_HGetDef( hPayload  , "creationTime", "" )
cAccessToken  := hb_HGetDef( hPayload  , "accessToken", "" )
cRefreshToken := hb_HGetDef( hPayload  , "refreshToken", "" )

msginfo ( "creationTime: " + cCreationTime + CRLF + ;
	  "accessToken:  " + cAccessToken + CRLF + ;
  	  "refreshToken: " + cRefreshToken )

IF Empty ( cAccessToken )
	MsgStop ("No accessToken, no authorization !!!")
ENDIF
I am not sure about the authorization yet, according to the description, the accessToken should be sent in the header "Authorization" as Bearer <accessToken>, while in Swagger it is sent without the word "Bearer". If the authorization does not work, try changing to:

Code: Select all

oRestApi:setRequestHeader ("Authorization", cAuth)
User avatar
nekbmm
Posts: 129
Joined: Sat Jul 16, 2016 3:16 am
DBs Used: DBF,SQLite
Location: Ivanjica, Serbia

Re: consumo de API REST con HMG

Post by nekbmm »

Thanks edk, it's working now !
User avatar
edufloriv
Posts: 247
Joined: Thu Nov 08, 2012 3:42 am
DBs Used: DBF, MariaDB, MySQL, MSSQL, MariaDB
Location: PERU

Re: consumo de API REST con HMG

Post by edufloriv »

Edk it works !! - Thanks a lot mi friend if you visit Perú some day, I will be your guide.

Here is the response:
respuesta-nubefact.png
respuesta-nubefact.png (56.59 KiB) Viewed 4257 times
Works perfectly !!


Best regards !!

------------------------------------------------------------------------------------------------------------

Edk muchas gracias, funciona. Si visitas algún dia Perú yo seré tu guia, tenlo por seguro.

Esta es la respuesta de la Api-Rest:
respuesta-nubefact.png
respuesta-nubefact.png (56.59 KiB) Viewed 4257 times
Trabaja perfecto !!

Saludos y un abrazo.

Eduardo Flores Rivas


LIMA - PERU
edk
Posts: 999
Joined: Thu Oct 16, 2014 11:35 am
Location: Poland

Re: consumo de API REST con HMG

Post by edk »

edufloriv wrote: Tue Mar 23, 2021 2:19 am Si visitas algún dia Perú yo seré tu guia, tenlo por seguro.
Gracias, mi tocayo.
jparada
Posts: 433
Joined: Fri Jan 23, 2009 5:18 pm

Re: consumo de API REST con HMG

Post by jparada »

Hi,
I am trying to work with Monday API and I'm guiding myself in the example code, it doesn't generate an error, but I don't get any response, I know that the token and query are correct because I have tested them in the Monday live playground and I get the expected results, this is an example of how they perform the request with the VBA language

Code: Select all

Public Pass As Variant

Sub monday()
 Dim monday As New MSXML2.ServerXMLHTTP60
 Dim response As Variant
 Dim status As Variant
 Dim query As String
 
 query = " { ""query"" : ""{boards(ids: xxxxx){views{name}}}""} "
 
    With monday
        .Open "POST", myurl , False
        .SetRequestHeader "Content-Type", "application/json"
        .SetRequestHeader "Accept", "application/json"
        .SetRequestHeader "Authorization", mytoken
        .Send query
        response = .ResponseText
        status = .status & " | " & .StatusText

        MsgBox response
        MsgBox status
        
   
    End With
and this is the code that I am trying

Code: Select all

Function main 
  Local cUrl := "https://api.monday.com/v2"  
  Local nTimeOut := 20  // seconds
  Local oRestApi
  Local cReturn, cResponse
  Local cAuth := "TOKEN"

  oRestApi := Win_OleCreateObject( "MSXML2.ServerXMLHTTP" )
  oRestApi:setTimeouts(nTimeout * 1000 /* nResolve */ , nTimeout * 1000 /* nConnect*/ , nTimeout * 1000 /* nSend */, nTimeout * 1000 /* nReceive */ )
  
  If Empty( oRestApi )
	  ? "Error al inicializar..."
	  Return NIL
  Endif

  query = ' { ""query"" : ""{boards(ids: 1673472238){name views{name}}}""} '

  BEGIN SEQUENCE WITH { |o| Break(o) }	  

    oRestApi:Open( "POST", cUrl, .F. )	  
    oRestApi:setRequestHeader( "Content-Type", "application/json" )
    oRestApi:setRequestHeader( "Accept", "application/json" )
    oRestApi:setRequestHeader( "Authorization", cAuth )	
    oRestApi:Send( query )

    ? cReturn  := hb_jsonDecode( oRestApi:ResponseText() )

    ? hb_jsonDecode( oRestApi:ResponseBody() )
      
  RECOVER USING oErr
	  
    cReturn := "Error!" + hb_eol() + If ( ValType( oErr ) = 'O', oErr:Description, oErr )
 
  END SEQUENCE
 	  
  oRestApi := NIL

Return
what's wrong with my test?

I appreciate any help

Regards,
Javier
jparada
Posts: 433
Joined: Fri Jan 23, 2009 5:18 pm

Re: consumo de API REST con HMG

Post by jparada »

Hi,

I advanced just a little more just adding

Code: Select all

 oRestApi:Send( hb_jsonEncode ( query ) )
I get a 200 code in the request, but I don't get the correct result

doing a test by command line with curl the query should be escaped something like this:

Code: Select all

 "{\"query\":\"{ boards (ids: 1673472238){name views{name}}}\"}"
how can i send something like that with harbour, this doesn't work either:

Code: Select all

query :=  '{"query": "{boards (ids: 1673472238){name views{name}}}"}'
Any idea?

Regards,
Javier
martingz
Posts: 408
Joined: Wed Nov 18, 2009 11:14 pm
Location: Mexico

Re: consumo de API REST con HMG

Post by martingz »

Maybe this

#xcommand TEXT TO VAR <var> => #pragma __stream|<var>:=%s


TEXT TO VAR cQuery
"{\"query\":\"{ boards (ids: 1673472238){name views{name}}}\"}"
ENDTEXT
jparada
Posts: 433
Joined: Fri Jan 23, 2009 5:18 pm

Re: consumo de API REST con HMG

Post by jparada »

Hi Martín,

It was my fault because i was sending the query encoded as json, and that's why it sent the malformed query

and no need to escape the characters.

There will be some advantage or disadvantage to make the request with cURL against XMLHttpRequest, just to know...

Regards,
Javier
Post Reply