SWAGGER-UI para documentar nuestras API.

SWAGGER-UI para documentar nuestras API.

Postby thefull » Mon Mar 04, 2024 7:28 pm

Buenas, hace tiempo que no estoy por aquí, pero hace unos días , charlando con viejos conocidos de por estos lares, y estando yo
dándole a Java, usamos una herramienta llamada SWAGGER.

Dicha herramienta, si habéis usado APIREST, es bastante común. Caí en la cuenta, si era posible usarla con nuestras APIs de Harbour, y et voila!
PASOS RÁPIDOS
==================================================================
Code: Select all  Expand view

# Creamos docker
docker pull swaggerapi/swagger-ui

# Abrimos el puerto 80, donde correrá swagger-ui y atacará a nuestro api en el puerto 8002
docker run -p 80:8080 -e SWAGGER_JSON_URL=http://192.168.1.107:8002/v3/api-docs swaggerapi/swagger-ui
 


Tendremos que tener un endpoint en nuestra API, /v3/api-docs, que deberá devolver un json con la especificacion de nuestra API, en formato OpenAPI

Bien, en Harbour será tan sencillo como especificar nuestra , vaya, especificación, os dejo el típico hola mundo ;
Lógicamente, el endpoint /v3/api-docs de vuestro servidor de API tiene que saltar a esta función
Code: Select all  Expand view

/**
 * Un simple HOLA MUNDO en el mundo de la APIREST
**/

function swagger()
    Local hHash := {=>}
    Local hInfo
    Local hPaths
    Local hComponents

    UAddHeader( "Access-Control-Allow-Origin", "*" )  
    UAddHeader( "Access-Control-Allow-Credentials", "true" )  
    UAddHeader( "Access-Control-Allow-Headers", "authorization, content-type" )  
     
    UAddHeader( "Content-Type", "application/json;charset=UTF-8" )
   
    hHash["openapi"] := "3.0.0"
   
    // Seccion Info
    hInfo := {=>}
    hInfo["title"] := "API FROM Harbour by Thefull"
    hInfo["version"] :=  "0.0.1"
    hHash["info"] := hInfo

 // Sección "paths"
    hPaths := {=>}
    hPaths["/{id}"] := {=>}
    hPaths["/{id}"]["get"] := {=>}
    hPaths["/{id}"]["get"]["summary"] := "Obtener elemento por ID"
    hPaths["/{id}"]["get"]["parameters"] := array(1)
    hPaths["/{id}"]["get"]["parameters"][1] := {=>}
    hPaths["/{id}"]["get"]["parameters"][1]["name"] := "id"
    hPaths["/{id}"]["get"]["parameters"][1]["in"] := "path"
    hPaths["/{id}"]["get"]["parameters"][1]["required"] := .T.
    hPaths["/{id}"]["get"]["parameters"][1]["schema"] := {=>}
    hPaths["/{id}"]["get"]["parameters"][1]["schema"]["type"] := "integer"
    hPaths["/{id}"]["get"]["responses"] := {=>}
    hPaths["/{id}"]["get"]["responses"]["200"] := {=>}
    hPaths["/{id}"]["get"]["responses"]["200"]["description"] := "OK"
    hPaths["/{id}"]["get"]["responses"]["200"]["content"] := {=>}
    hPaths["/{id}"]["get"]["responses"]["200"]["content"]["application/json"] := {=>}
    hPaths["/{id}"]["get"]["responses"]["200"]["content"]["application/json"]["schema"] := {=>}
    hPaths["/{id}"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] := "#/components/schemas/TaxIdTypeDTO"
    hHash["paths"] := hPaths

    // Sección "components"
    hComponents := {=>}
    hComponents["schemas"] := {=>}
    hComponents["schemas"]["TaxIdTypeDTO"] := {=>}
    hComponents["schemas"]["TaxIdTypeDTO"]["type"] := "object"
    hComponents["schemas"]["TaxIdTypeDTO"]["properties"] := {=>}
    hComponents["schemas"]["TaxIdTypeDTO"]["properties"]["id"] := {=>}
    hComponents["schemas"]["TaxIdTypeDTO"]["properties"]["id"]["type"] := "integer"
    hComponents["schemas"]["TaxIdTypeDTO"]["properties"]["name"] := {=>}
    hComponents["schemas"]["TaxIdTypeDTO"]["properties"]["name"]["type"] := "string"
    // Otros campos de TaxIdTypeDTO aquí, si es necesario

    hHash["components"] := hComponents

 return hb_jsonEncode( hHash )  

 


El resultado;
Image

Espero os guste y os sea de utilidad. Nos vemos!!

Documentacion -
-> https://github.com/swagger-api/swagger- ... llation.md
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: SWAGGER-UI para documentar nuestras API.

Postby Antonio Linares » Tue Mar 05, 2024 6:36 am

Muchas gracias Rafa! :-)
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Antonio Linares
Site Admin
 
Posts: 42099
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain

Re: SWAGGER-UI para documentar nuestras API.

Postby Joaquim Ferrer » Tue Mar 05, 2024 10:37 am

Despues de la excelente puerta abrierta por Rafa, voy a explicar mi experiencia e intentar 'traducir' para el resto de los mortales esta idea ...

Lo primero docker - no confundir con la marca de pantalones dockers, que hasta hace poco era lo unico que me sonaba ;)-

La forma más facil que he encontrado para entrar en el maravilloso mundo de los contenedores virtuales es instalando su aplicación de escritorio

Me ha servido esta guia https://www.ionos.es/digitalguide/servidores/configuracion/instalar-docker-en-windows-10/

Una vez tenemos arrancado y funcionando docker, seguir los pasos indicados :

Code: Select all  Expand view

# Creamos docker
docker pull swaggerapi/swagger-ui

# Abrimos el puerto 80, donde correrá swagger-ui y atacará a nuestro api en el puerto 8002
docker run -p 80:8080 -e SWAGGER_JSON_URL=http://192.168.1.107:8002/v3/api-docs swaggerapi/swagger-ui
 


Lógicamente adaptar la IP 192.168.1.107 a nuestra maquina ( y puerto si deseamos cambiar )

Cuando nos dice que swagger-ui atacará a nuestra api en el puerto 8002, esto quiere decir que necesitamos un servidor en dicho puerto que 'escuche'

Image

Personalmente hace tiempo desarrollé mi propio servidor http en harbour, basado en el publicado en las contrib hbhttpd de Mindaugas y en el que he añadido el siguiente endpoint :
Code: Select all  Expand view
"/v3/api-docs"  => {|| Swagger() }, ;


Al llamar a dicho endpoint, el servidor responderá con la llamada a la funcion Suagger() propuesta por Rafa, que es la encargada de devolver el json en el formato necesario (OPenApi)

Supongo que será igualmente fácil adaptar a otros servidores basados en harbour (UT de Charly, etc...) y también voy a probar de adaptar para Apache + CGI

El resultado, funcionando !
Image

Saludos
Fivewinner desde 1.9, programador PHP y Javascript, PWA & HTML5 evangelista
User avatar
Joaquim Ferrer
 
Posts: 105
Joined: Sat Jan 14, 2012 3:46 pm
Location: Barcelona

Re: SWAGGER-UI para documentar nuestras API.

Postby thefull » Tue Mar 05, 2024 2:18 pm

Genial Quim! Muchas gracias para explicarlo tan detalladamente.
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: SWAGGER-UI para documentar nuestras API.

Postby Marc Venken » Tue Mar 05, 2024 9:59 pm

So, This is for building Swagger docu..

I'm trying to connect to MailChimpt-API that is based on Swagger, so maybe you guys can help me

Code: Select all  Expand view

cUrl:=  "https://us8.api.mailchimp.com/3.0/campaigns? --user anystring:cCode "
MsgRun( cUrl, "READING FORUM PAGE", { || uResponse := WebPageContents( cUrl, .t. ) } )
St := memowrit("c:\marc32\APICHIMP.txt",uResponse)
 


The text "user" is not converted, maybe it need to be a user name ?
The cCode = API code from Mailchimp

I get following error :

{"type":"https://mailchimp.com/developer/marketing/docs/errors/","title":"API Key Invalid","status":401,"detail":"Your request did not include an API key.","instance":"5cd6..."}

Do you call swagger api's a other way ?
Marc Venken
Using: FWH 23.04 with Harbour
User avatar
Marc Venken
 
Posts: 1434
Joined: Tue Jun 14, 2016 7:51 am
Location: Belgium

Re: SWAGGER-UI para documentar nuestras API.

Postby thefull » Wed Mar 06, 2024 5:28 pm

Hi.

Quim and I, connect using Postman, but your have documentation in https://mailchimp.com/developer/marketi ... resources/

Your need {apikey}, etc..

Example using curl from command line;

curl -X GET \
'https://${dc}.api.mailchimp.com/3.0/?fields=<SOME_ARRAY_VALUE>&exclude_fields=<SOME_ARRAY_VALUE>' \
--user "anystring:${apikey}"'

Regards
Saludos
Rafa Carmona ( rafa.thefullARROBAgmail.com___quitalineas__)
User avatar
thefull
 
Posts: 731
Joined: Fri Oct 07, 2005 7:42 am
Location: Barcelona

Re: SWAGGER-UI para documentar nuestras API.

Postby Joaquim Ferrer » Wed Mar 06, 2024 6:14 pm

Dear Marc

Mailchimp exposes Marketing API (and others) in OAS format at https://api.mailchimp.com/schema/3.0/Swagger.json

This format can be read with Postman https://www.postman.com/

You can import from File -> Import -> Link -> https://api.mailchimp.com/schema/3.0/Swagger.json

Then you are ready to use their services

Remember that you have to register an Api Key
https://mailchimp.com/developer/marketing/guides/quick-start/

Image

Regards
Fivewinner desde 1.9, programador PHP y Javascript, PWA & HTML5 evangelista
User avatar
Joaquim Ferrer
 
Posts: 105
Joined: Sat Jan 14, 2012 3:46 pm
Location: Barcelona

Re: SWAGGER-UI para documentar nuestras API.

Postby Marc Venken » Fri Mar 08, 2024 9:56 pm

Hi,

I gave a quick look in Postman. Heavy for a not programmer like me ))))

But I was able to get information from the command line with cUrl. Of cource the implementation info FW will be the goal.

Looking into the forum it seems that we have to link extra 2 libs and place a DLL into the program folder. Do any of you use it from inside FW ?

I also wonder why you are using Postman ? FW Can handle cUrl as far as I can tell. What is your reason or benifit ?

Thanks for the help in this project !
Marc Venken
Using: FWH 23.04 with Harbour
User avatar
Marc Venken
 
Posts: 1434
Joined: Tue Jun 14, 2016 7:51 am
Location: Belgium

Re: SWAGGER-UI para documentar nuestras API.

Postby Marc Venken » Sat Mar 09, 2024 9:07 pm

I got it working with this code from Otto (Eng. Forum) :

Code: Select all  Expand view

   DCOM := 'cmd /c curl -sS https://us8.api.mailchimp.com/3.0/ping --user anystring:'+cApi+' > clogrooms.txt'  // Working
   DCOM := 'cmd /c curl -sS https://us8.api.mailchimp.com/3.0/campaigns --user anystring:'+cApi+' > clogrooms.txt'  // Working
   WAITRUN( DCOM, 0)
   cFileName := "clogrooms.txt"
   cMemo := MEMOREAD(cFileName)

   msginfo("File created")

   hb_JsonDecode( cMemo, @hHash )
   XBrowser HashTree ( hHash ) FASTEDIT

 


Now the hard part of getting all those fields from the HASH
Marc Venken
Using: FWH 23.04 with Harbour
User avatar
Marc Venken
 
Posts: 1434
Joined: Tue Jun 14, 2016 7:51 am
Location: Belgium

Re: SWAGGER-UI para documentar nuestras API.

Postby Marc Venken » Tue Mar 19, 2024 10:14 pm

I can read several data with the API, but struggle with the one that can change a TAG (like a groupname) into Mailchimp.

This is working, and I get the tags from a email

DCOM := 'cmd /c curl -sS https://us8.api.mailchimp.com/3.0/lists ... ail+'/tags --user anystring:'+cApi+' > clogrooms.txt'

In order to add a Tag this should be executed, but I allways fale in passing the correct data

This is NOT working

DCOM := 'cmd /c curl -sS https://us8.api.mailchimp.com/3.0/lists ... members/';
+cSecure_Email+'/tags --user anystring:';
+cApi+'-d tags:'+aTags+',is_syncing:false';
+' > clogrooms.txt'

and Mailchimp api says :

curl -X POST \
https://${dc}.api.mailchimp.com/3.0/lists/{list_id}/members/{subscriber_hash}/tags \
--user "anystring:${apikey}"' \
-d '{"tags":[],"is_syncing":false}'

By any change that somebody knows how to do it ?
Marc Venken
Using: FWH 23.04 with Harbour
User avatar
Marc Venken
 
Posts: 1434
Joined: Tue Jun 14, 2016 7:51 am
Location: Belgium


Return to FiveWin para Harbour/xHarbour

Who is online

Users browsing this forum: No registered users and 50 guests