Basic API Definition
syntax = "proto3";
package helloworld.v1;
option go_package = "helloworld/api/helloworld/v1;v1";
import "google/api/annotations.proto";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
get: "/helloworld/{name}"
};
}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
import "google/api/annotations.proto";
service UserService {
// GET request
rpc GetUser (GetUserRequest) returns (User) {
option (google.api.http) = {
get: "/v1/users/{id}"
};
}
// POST request with body
rpc CreateUser (CreateUserRequest) returns (User) {
option (google.api.http) = {
post: "/v1/users"
body: "*"
};
}
// PUT request
rpc UpdateUser (UpdateUserRequest) returns (User) {
option (google.api.http) = {
put: "/v1/users/{id}"
body: "*"
};
}
// DELETE request
rpc DeleteUser (DeleteUserRequest) returns (google.protobuf.Empty) {
option (google.api.http) = {
delete: "/v1/users/{id}"
};
}
}
message GetUserRequest {
string id = 1;
}
message CreateUserRequest {
string name = 1;
string email = 2;
int32 age = 3;
}
message UpdateUserRequest {
string id = 1;
string name = 2;
string email = 3;
int32 age = 4;
}
message DeleteUserRequest {
string id = 1;
}
message User {
string id = 1;
string name = 2;
string email = 3;
int32 age = 4;
int64 created_at = 5;
int64 updated_at = 6;
}
Advanced HTTP Bindings
Path Parameters
Capture variables from the URL path:Query Parameters
All fields not in the path become query parameters:Request Body
Specify which fields should be in the request body:Multiple HTTP Bindings
Support multiple HTTP endpoints for one RPC method:Error Definitions
Define custom errors using enums with Kratos error extensions:api/helloworld/v1/errors.proto
Validation Rules
Add validation rules using protoc-gen-validate:Metadata Service
Kratos provides a built-in metadata service for API introspection:api/metadata/metadata.proto
Best Practices
Versioning
Always version your APIs (v1, v2) to allow backward compatibility
Naming
Use clear, consistent naming: GetUser, ListUsers, CreateUser, UpdateUser, DeleteUser
RESTful URLs
Follow REST conventions:
/v1/users/{id} not /v1/get_userError Handling
Define specific error codes for each failure case
Code Generation
After defining your APIs, generate the code:.pb.gofiles (protobuf messages)_http.pb.gofiles (HTTP bindings)_grpc.pb.gofiles (gRPC service definitions)_errors.pb.gofiles (error definitions)
Next Steps
Code Generation
Learn about protoc plugins and code generation
Service Implementation
Implement your service logic