gRPC JSON transcoding documentation with Swagger / OpenAPI
OpenAPI (Swagger) is a language-agnostic specification for describing REST APIs. gRPC JSON transcoding supports generating OpenAPI from transcoded RESTful APIs. The Microsoft.AspNetCore.Grpc.Swagger
package:
- Integrates gRPC JSON transcoding with Swashbuckle.
- Is experimental in .NET 7 to allow us to explore the best way to provide OpenAPI support.
Get started
To enable OpenAPI with gRPC JSON transcoding:
- Add a package reference to
Microsoft.AspNetCore.Grpc.Swagger
. The version must be 0.3.0-xxx or later. - Configure Swashbuckle in startup. The
AddGrpcSwagger
method configures Swashbuckle to include gRPC endpoints.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc().AddJsonTranscoding();
builder.Services.AddGrpcSwagger();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo { Title = "gRPC transcoding", Version = "v1" });
});
var app = builder.Build();
app.UseSwagger();
if (app.Environment.IsDevelopment())
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
app.MapGrpcService<GreeterService>();
app.Run();
Note
For guidance on adding packages to .NET apps, see the articles under Install and manage packages at Package consumption workflow (NuGet documentation). Confirm correct package versions at NuGet.org.
Add OpenAPI descriptions from .proto
comments
Generate OpenAPI descriptions from comments in the .proto
contract, as in the following example:
// My amazing greeter service.
service Greeter {
// Sends a greeting.
rpc SayHello (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
get: "/v1/greeter/{name}"
};
}
}
message HelloRequest {
// Name to say hello to.
string name = 1;
}
message HelloReply {
// Hello reply message.
string message = 1;
}
To enable gRPC OpenAPI comments:
- Enable the XML documentation file in the server project with
<GenerateDocumentationFile>true</GenerateDocumentationFile>
. - Configure
AddSwaggerGen
to read the generated XML file. Pass the XML file path toIncludeXmlComments
andIncludeGrpcXmlComments
, as in the following example:
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo { Title = "gRPC transcoding", Version = "v1" });
var filePath = Path.Combine(System.AppContext.BaseDirectory, "Server.xml");
c.IncludeXmlComments(filePath);
c.IncludeGrpcXmlComments(filePath, includeControllerXmlComments: true);
});
To confirm that Swashbuckle is generating OpenAPI with descriptions for the RESTful gRPC services, start the app and navigate to the Swagger UI page:
Additional resources
Atsiliepimai
https://aka.ms/ContentUserFeedback.
Jau greitai: 2024 m. palaipsniui atsisakysime „GitHub“ problemų, kaip turiniui taikomo atsiliepimų mechanizmo, ir pakeisime jį nauja atsiliepimų sistema. Daugiau informacijos žr.Pateikti ir peržiūrėti atsiliepimą, skirtą