Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 39 ยท Getting Started

Your First gRPC Service: Hello World

Build a complete Hello World gRPC service: write the contract, implement the server, call it from a client. Real code is shown, plus a runnable loopback TCP stand-in.

Time to put the pieces together. In this lesson you will write a tiny greeting service end to end: the contract, the server, and the client. The real Go and Python code is shown read-only, because gRPC libraries cannot run on this site. After each real listing, a runnable Go stand-in does the same job over a real TCP connection on the loopback interface, using the message framing from how gRPC uses HTTP/2.

Make sure you have the tools from installing protoc and plugins if you want to follow along on your own machine.

Step 1: the contract

PROTO
// proto/greeter/v1/greeter.proto
syntax = "proto3";

package greeter.v1;
option go_package = "example.com/hello/gen/greeter/v1;greeterv1";

service Greeter {
  rpc SayHello(HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

Generate code with the command from the previous lesson. You now have types HelloRequest and HelloReply, a GreeterClient interface with a SayHello method, and a GreeterServer interface you implement.

Step 2: the server in Go (read-only)

Go
package main

import (
	"context"
	"log"
	"net"

	"google.golang.org/grpc"
	pb "example.com/hello/gen/greeter/v1"
)

type server struct {
	pb.UnimplementedGreeterServer
}

func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) {
	return &pb.HelloReply{Message: "Hello, " + req.GetName() + "!"}, nil
}

func main() {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatal(err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	log.Println("listening on", lis.Addr())
	log.Fatal(s.Serve(lis))
}

Points to notice:

  • Embedding UnimplementedGreeterServer means a method you forget to implement returns UNIMPLEMENTED instead of failing to compile when the contract grows.
  • Getters such as GetName() are nil-safe, so a missing request never panics.
  • RegisterGreeterServer wires your struct to the method paths. The details are in implementing a server.

Step 3: the client in Go (read-only)

Go
package main

import (
	"context"
	"log"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	pb "example.com/hello/gen/greeter/v1"
)

func main() {
	conn, err := grpc.NewClient("localhost:50051",
		grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	client := pb.NewGreeterClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	reply, err := client.SayHello(ctx, &pb.HelloRequest{Name: "Ada"})
	if err != nil {
		log.Fatal(err)
	}
	log.Println(reply.GetMessage())
}

Expected output when the server runs: Hello, Ada!. The insecure credentials mean no TLS, which is fine for a local experiment and never for production; see the security chapter on the track page. The context carries a one-second deadline.

The same thing in Python (read-only)

Python
# server.py
from concurrent import futures
import grpc
import greeter_pb2, greeter_pb2_grpc

class Greeter(greeter_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return greeter_pb2.HelloReply(message=f"Hello, {request.name}!")

server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
greeter_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()
Python
# client.py
import grpc
import greeter_pb2, greeter_pb2_grpc

with grpc.insecure_channel("localhost:50051") as channel:
    stub = greeter_pb2_grpc.GreeterStub(channel)
    reply = stub.SayHello(greeter_pb2.HelloRequest(name="Ada"), timeout=1.0)
    print(reply.message)

Same contract, two languages, no shared code besides the .proto file. That is the multi-language promise of gRPC.

Stand-in 1: a real TCP server and client

This runnable Go program starts a TCP server on a random loopback port, and a client that sends one framed request. Messages are JSON (not protobuf) and the transport is plain TCP (not HTTP/2), but the structure matches: listen, accept, read a frame, dispatch, write a frame.

Go Stand-in: Hello over loopback TCP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The port is random, so the program prints only the reply. The real grpc.NewServer() does the same accept loop for you, plus HTTP/2, header parsing, protobuf, deadlines and status codes.

Stand-in 2: serving many callers

A server handles many clients at once. Here five clients call the stand-in server concurrently, and the output is sorted so it stays deterministic.

Go Stand-in: concurrent clients

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Troubleshooting a first call

  • connection refused. The server is not running, or the port differs.
  • UNIMPLEMENTED. The server did not register the service, or the client and server contracts use different package or service names, so the method path does not match.
  • DEADLINE_EXCEEDED. The server was too slow or unreachable for the given timeout.
  • UNAVAILABLE with TLS or HTTP/2 messages. One side uses TLS and the other does not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why embed UnimplementedGreeterServer in your Go server struct?

    The embedded type supplies default methods that return an UNIMPLEMENTED status.
  2. 2. What identifies which method a gRPC request is for?

    The path is /package.Service/Method, built from the contract.
  3. 3. What do the generated Go and Python programs share?

    Each language generates its own code from the same contract; messages interoperate on the wire.
  4. 4. What are insecure credentials appropriate for?

    Insecure means plaintext HTTP/2 without TLS.

Summary

  • A first service needs a contract, a generated package, a server that implements the interface and a client that calls the stub.
  • Servers register a service implementation; clients create a channel and a stub from it.
  • Go and Python implementations interoperate because both follow the same contract and wire format.
  • Always set a deadline on client calls.
  • Our TCP stand-in mirrors the structure of the real flow using the standard library only.

Next: Messages and Scalar Types