Designbest Rest API: differenze tra le versioni

Da Webmobili Wiki.
 
(7 versioni intermedie di uno stesso utente non sono mostrate)
Riga 107: Riga 107:


Andare su ''Properties'' e nella ''Build Action'' segnare ''None''.
Andare su ''Properties'' e nella ''Build Action'' segnare ''None''.
== API Reference per clienti ==
https://apidocs.designbest.com/
Il progetto deriva da qui
https://github.com/swagger-api/swagger-ui
utilizzando la base ''html/js'' ho
* Cambiato le <code>favicon</code>
* Aggiunto il file <code>designbest-swagger.css</code>
* <div>Modificato il file <code>index.html</code> per aggiungere nell'<code><head></code>
<syntaxhighlight lang="html">
<link rel="stylesheet" type="text/css" href="designbest-swagger.css" />
</syntaxhighlight>
</div>
* <div>Sostituito <code>swagger.json</code> con quello generato dal progetto '''Designbest REST API Core''' <code>https://apicore.dbdemo47.com/designbest/clients/swagger.json</code> <br/>
stando attenti a modificare la stringa
<pre>
  "servers": [
    {
      "url": "https://apicore.dbdemo47.com"
    }
  ],
</pre>
in
<pre>
  "servers": [
    {
      "url": "https://apicore.designbest.com"
    }
  ],
</pre>
</div>
=== Requisiti lato cliente - CORS (Cross-Origin Resource Sharing) ===
Il server che ospita le API di Designbest richiede che le richieste siano effettuate da un client che dichiari i seguenti <code>header http</code>:
<syntaxhighlight lang="bash">
Access-Control-Allow-Origin:  *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
</syntaxhighlight>
Nel caso di un sito PHP basta aggiungere le seguenti righe all'<code>.htaccess</code>
<syntaxhighlight lang="bash">
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin *
    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>
</syntaxhighlight>

Versione attuale delle 10:30, 28 lug 2025

Access Token

[modifica]

Token valido 100 anni

[modifica]

Per servizi che hanno bisogno di un token fisso e non possono fare la richiesta ogni volta (es. Zapier),
ecco un token che dura 100 anni:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c3IiOiJkZXNpZ25iZXN0cmVzdCIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6IkFkbWluIiwiZXhwIjo0OTA1MzIxMDk1LCJpc3MiOiJ3ZWJtb2JpbGkiLCJhdWQiOiJkZXNpZ25iZXN0In0.BT49K_oZyq9JW6mqNKHeGj3tGlIKvQorUlBcO7gdbvY

Test

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c3IiOiJkZXNpZ25iZXN0cmVzdCIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6IkFkbWluIiwiZXhwIjo0OTA1ODUyMTAxLCJpc3MiOiJ3ZWJtb2JpbGkiLCJhdWQiOiJkZXNpZ25iZXN0In0.v6mu9ShFdlIl1Xsq7Z4YYc09LgL53T2fYyibjmA4RGc

Configurazione di Swagger

[modifica]

Nel file Program.cs configurare così

const string adminDocName = "v1";
const string clientsDocName = "clients";
builder.Services.AddSwaggerGen(
	opt => {
		// SwaggerDoc Admin
		opt.SwaggerDoc(adminDocName, new() {
			Title = "Designbest REST API",
			Description = "La Designbest REST API fornisce un accesso completo e flessibile al portale leader mondiale dell'arredamento.",
			Version = "v1",
			Contact = new() { Email = "info@designbest.com", Name = "Webmobili s.r.l." }
		});
		// SwaggerDoc Client
		opt.SwaggerDoc("clients", new() {
      Title = "Designbest REST API for clients",
      Description = "La Designbest REST API fornisce un'interfaccia di accesso dati completa e flessibile sul portale leader mondiale dell'arredamento.",
      Version = "v1",
      Contact = new() { Email = "info@designbest.com", Name = "Webmobili s.r.l." }
    });
		var tokenService = new TokenService(builder.Configuration, builder.Environment);
    const string securitySchemeName = JwtBearerDefaults.AuthenticationScheme;
    opt.AddSecurityDefinition(securitySchemeName, new() {
			In = ParameterLocation.Header,
			Description = "Please enter a valid token like " + tokenService.GetToken()?.AccessToken,
			Name = "Authorization",
			Type = SecuritySchemeType.Http,
			BearerFormat = "JWT",
			Scheme = "Bearer"
		});
		opt.AddSecurityRequirement(new() {
			{
				new() {
					Reference = new() {
						Type = ReferenceType.SecurityScheme,
						Id = securitySchemeName
          }
				},
				Array.Empty<string>()
			}
		});

		var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
		opt.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFile));
	}
);

e di sotto, per poter cambiare il nome dell'endpoint della documentazione in /designbest e personalizzare la grafica

app.UseSwagger(options => {
  options.RouteTemplate = "designbest/{documentName}/swagger.json";
});
if (app.Environment.IsDevelopment() || app.Environment.IsStaging()) {
	app.UseSwaggerUI(options => {
		options.DocumentTitle = "Designbest REST API";
    options.InjectStylesheet("/css/designbest-swagger.css");
		options.InjectJavascript("/js/swagger-custom.js");
		options.RoutePrefix = "designbest";
    options.SwaggerEndpoint($"/designbest/{adminDocName}/swagger.json", "Designbest REST API");	// "v1" corrisponde al primo parametro di SwaggerDoc("v1", new() {
    options.SwaggerEndpoint($"/designbest/{clientsDocName}/swagger.json", "Designbest REST API for clients");	// "clients" corrisponde al primo parametro di SwaggerDoc("client", new() {
  });
}
// ...
app.MapStaticAssets();
  • RouteTemplate, RoutePrefix e SwaggerEndpoint() sono collegati e servono a cambiare il nome default per raggiungere la url della documentazione
  • InjectStylesheet() e InjectJavascript() servono a personalizzare la grafica.
    Perché questi funzionino è necessario attivare app.UseStaticFiles(); e creare la cartella wwwroot che conterrà le cartelle css e js

  • Nel file Properties/launchSettings.json modificare i campi launchUrl con la stringa "swagger" => "designbest".

Verb PUT e DELETE

[modifica]

A quanto pare esiste un modulo chiamato WebDAV su Windows Server che intercetta tutte le chiamate PUT e DELETE e non permette che arrivino alla RestAPI.

Il modulo deve essere disattivato dal sito tramite il web.config.

Creare nella solution un file web.release.config col seguente codice:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
	<location>
		<system.webServer>
			<modules xdt:Transform="Insert">
				<remove name="WebDAVModule" />
			</modules>
			<handlers>
				<remove name="WebDAV" xdt:Transform="Insert" />
			</handlers>
		</system.webServer>
	</location>
</configuration>

Andare su Properties e nella Build Action segnare None.


API Reference per clienti

[modifica]

https://apidocs.designbest.com/

Il progetto deriva da qui

https://github.com/swagger-api/swagger-ui

utilizzando la base html/js ho

  • Cambiato le favicon
  • Aggiunto il file designbest-swagger.css
  • Modificato il file index.html per aggiungere nell'<head>
<link rel="stylesheet" type="text/css" href="designbest-swagger.css" />

stando attenti a modificare la stringa

  "servers": [
    {
      "url": "https://apicore.dbdemo47.com"
    }
  ],

in

  "servers": [
    {
      "url": "https://apicore.designbest.com"
    }
  ],

Requisiti lato cliente - CORS (Cross-Origin Resource Sharing)

[modifica]

Il server che ospita le API di Designbest richiede che le richieste siano effettuate da un client che dichiari i seguenti header http:

Access-Control-Allow-Origin:  *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization

Nel caso di un sito PHP basta aggiungere le seguenti righe all'.htaccess

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin *
    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>