Skip to main content

API Definition

Kratos implements REST and gRPC as the transport protocols. We mainly follow the API Design Guide from Google.

You could define REST API and gRPC API in proto files and generate Go codes from these files.

API Definition

You could define REST API and gRPC API in Protobuf IDL.


syntax = "proto3";

package helloworld.v1;

import "google/api/annotations.proto";

option go_package = ";v1";
option java_multiple_files = true;
option java_package = "dev.kratos.api.helloworld.v1";
option java_outer_classname = "HelloWorldProtoV1";

// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
// To define GET API, map name to HelloRequest
get: "/helloworld/{name}",
// You could also add some additional APIs
additional_bindings {
// To define POST API, map body to HelloRequest
post: "/v1/greeter/say_hello",
body: "*",

// The request message contains the user's name.
message HelloRequest {
string name = 1;

// The response message contains the greetings
message HelloReply {
string message = 1;

API Generation

# To generate proto template
kratos proto add api/helloworld/v1/greeter.proto
# To generate client codes
kratos proto client api/helloworld/v1/greeter.proto
# To generate server codes
kratos proto server api/helloworld/v1/greeter.proto -t internal/service
| |____helloworld
| | |____v1
| | | |____greeter.pb.go
| | | |____greeter.proto
| | | |____greeter_http.pb.go
| | | |____greeter_grpc.pb.go

| |____service
| | |____greeter.go

API Register

HTTP API is an http.Handler, which is generated by protoc-gen-go-http plugin, can be registered into HTTP Server.

import ""

greeter := &GreeterService{}
srv := http.NewServer(http.Address(":8000"))
srv.HandlePrefix("/", v1.NewGreeterHandler(greeter))

gRPC API is a gRPC Register, which is generated by protoc-gen-go-grpc plugin, can be registered into GRPC Server.

import ""

greeter := &GreeterService{}
srv := grpc.NewServer(grpc.Address(":9000"))
v1.RegisterGreeterServer(srv, greeter)