### Install Fastify and Connect Dependencies Source: https://connectrpc.com/docs/node/getting-started Install Fastify, the Connect Node.js plugin, and the Connect Fastify plugin to get started. ```bash $ npm install fastify @connectrpc/connect-node @connectrpc/connect-fastify ``` -------------------------------- ### Project Setup and Installation Commands Source: https://connectrpc.com/docs/web/getting-started These commands are used to create a new Vite React project, configure npm registries, install necessary ConnectRPC packages, and start the development server. ```bash $ npm create vite@latest -- connect-example --template react-ts $ cd connect-example $ npm config set @buf:registry https://buf.build/gen/npm/v1/ $ npm install @buf/connectrpc_eliza.bufbuild_es @connectrpc/connect @connectrpc/connect-web $ npm run dev ``` -------------------------------- ### Install Connect and Protobuf Tools Source: https://connectrpc.com/docs/go/getting-started Installs the necessary code generation tools for Connect and Protobuf. Ensure these tools are in your PATH after installation. ```bash $ mkdir connect-go-example $ cd connect-go-example $ go mod init example $ go install github.com/bufbuild/buf/cmd/buf@latest $ go get -tool google.golang.org/protobuf/cmd/protoc-gen-go@latest $ go get -tool connectrpc.com/connect/cmd/protoc-gen-connect-go@latest ``` -------------------------------- ### Install Dependencies and Run Server Source: https://connectrpc.com/docs/go/getting-started Install necessary Connect-Go and Protovalidate dependencies and then run the server application. ```bash $ go get connectrpc.com/connect $ go get connectrpc.com/validate $ go get buf.build/go/protovalidate $ go run ./cmd/server/main.go ``` -------------------------------- ### Basic Fastify Server Setup with Connect Plugin Source: https://connectrpc.com/docs/node/server-plugins Set up a Fastify server and register the Connect RPC plugin. The plugin can be configured with interceptors and routes. This example includes the Protovalidate interceptor. ```typescript import { fastify } from "fastify"; import { fastifyConnectPlugin } from "@connectrpc/connect-fastify"; import { createValidateInterceptor } from "@connectrpc/validate"; import routes from "./connect"; async function main() { const server = fastify(); await server.register(fastifyConnectPlugin, { // Validation via Protovalidate is almost always recommended interceptors: [createValidateInterceptor()], routes, }); await server.listen({ host: "localhost", port: 8080 }); } // You can remove the main() wrapper if you set type: module in your package.json, // and update your tsconfig.json with target: es2017 and module: es2022. void main(); ``` -------------------------------- ### Install Connect-Query Source: https://connectrpc.com/docs/web/query Install the necessary packages for Connect-Query and Connect-Web using npm. ```bash npm install @connectrpc/connect-query @connectrpc/connect-web ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://connectrpc.com/docs/node/getting-started Sets up a new Node.js project with TypeScript and installs necessary Connect, Protobuf, and validation tools. ```bash mkdir connect-example cd connect-example npm init -y npm install typescript tsx npx tsc --init npm install @bufbuild/buf @bufbuild/protobuf @bufbuild/protoc-gen-es @connectrpc/connect @connectrpc/validate ``` -------------------------------- ### Start Development Server Source: https://connectrpc.com/docs/web/getting-started Starts the web server and opens the application in the browser. Auto-refreshes on code changes. ```bash npm run dev ``` -------------------------------- ### Initialize Vite Project Source: https://connectrpc.com/docs/web/getting-started Use this command to set up a new React TypeScript project with Vite for the Connect example. After creation, navigate into the project directory and install dependencies. ```bash $ npm create vite@latest -- connect-example --template react-ts $ cd connect-example $ npm install ``` -------------------------------- ### Run Connect-Kotlin Example Source: https://connectrpc.com/docs/kotlin/getting-started Use this command to run the example. The `--console=plain -q` flags prevent Gradle's progress bars from interfering with the chat output. ```bash $ gradle run --console=plain -q ``` -------------------------------- ### Install Fastify and Connect Dependencies Source: https://connectrpc.com/docs/node/server-plugins Install the necessary packages for Fastify, Connect, Connect Node, and the Connect Fastify plugin. ```bash $ npm install fastify @connectrpc/connect @connectrpc/connect-node @connectrpc/connect-fastify ``` -------------------------------- ### Install Buf CLI Source: https://connectrpc.com/docs/dart/generating-code Installs the Buf command-line interface using Homebrew. ```bash $ brew install bufbuild/buf/buf ``` -------------------------------- ### Install Next.js Dependencies Source: https://connectrpc.com/docs/node/server-plugins Install the necessary packages for Next.js integration with Connect RPC. ```bash $ npm install next@"^13.0.0" @connectrpc/connect @connectrpc/connect-node @connectrpc/connect-next ``` -------------------------------- ### Install Buf and Protobuf Compiler Plugin Source: https://connectrpc.com/docs/web/generating-code Installs Buf, the protoc-gen-es plugin, and Connect RPC runtime dependencies for local code generation. ```bash $ npm install --save-dev @bufbuild/buf @bufbuild/protoc-gen-es $ npm install @connectrpc/connect @connectrpc/connect-web @bufbuild/protobuf ``` -------------------------------- ### Basic Connect Router Setup Source: https://connectrpc.com/docs/node/implementing-services This snippet shows the basic setup for a Connect router registration function. It imports `ConnectRouter` and exports a default function that accepts the router. ```typescript import { ConnectRouter } from "@connectrpc/connect"; export default (router: ConnectRouter) => {} ``` -------------------------------- ### Run ASGI Server Source: https://connectrpc.com/docs/python/getting-started Start an ASGI server using 'uvicorn' to serve the ConnectRPC application. ```bash $ uv run uvicorn server:app ``` -------------------------------- ### Start the Connect RPC Server Source: https://connectrpc.com/docs/node/getting-started Run the TypeScript server file using tsx to start your Connect RPC server. ```bash $ npx tsx server.ts ``` -------------------------------- ### Install Express Dependencies Source: https://connectrpc.com/docs/node/server-plugins Install the necessary packages for Express integration, including Express itself, Connect, Connect Node, and Connect Express. ```bash $ npm install express @connectrpc/connect @connectrpc/connect-node @connectrpc/connect-express ``` -------------------------------- ### Run WSGI Server Source: https://connectrpc.com/docs/python/getting-started Start a WSGI server using 'gunicorn' to serve the ConnectRPC application. ```bash $ uv run gunicorn server:app ``` -------------------------------- ### Configure npm Registry and Install Connect Packages Source: https://connectrpc.com/docs/web/getting-started Configure npm to use the Buf Schema Registry for package lookups and then install the necessary Connect packages. This command generates the required types on the fly. ```bash $ npm config set @buf:registry https://buf.build/gen/npm/v1/ $ npm install @buf/connectrpc_eliza.bufbuild_es @connectrpc/connect @connectrpc/connect-web ``` -------------------------------- ### Create a Connect RPC Server with Fastify Source: https://connectrpc.com/docs/node/getting-started Set up a Fastify server and register the Connect RPC plugin. Includes an example of a basic HTTP endpoint and logging server status. ```typescript import { createValidateInterceptor } from "@connectrpc/validate"; import { fastify } from "fastify"; import { fastifyConnectPlugin } from "@connectrpc/connect-fastify"; import routes from "./connect"; async function main() { const server = fastify(); await server.register(fastifyConnectPlugin, { // Validation via Protovalidate is almost always recommended interceptors: [createValidateInterceptor()], routes, }); server.get("/", (_, reply) => { reply.type("text/plain"); reply.send("Hello World!"); }); await server.listen({ host: "localhost", port: 8080 }); console.log("server is listening at", server.addresses()); } // You can remove the main() wrapper if you set type: module in your package.json, // and update your tsconfig.json with target: es2017 and module: es2022. void main(); ``` -------------------------------- ### Run gRPC Client Example Source: https://connectrpc.com/docs/go/getting-started Execute the client application to test the gRPC protocol communication. Ensure the server is running in a separate terminal. ```bash $ go run ./cmd/client/main.go ``` -------------------------------- ### Implement ElizaService with ConnectRouter Source: https://connectrpc.com/docs/node/getting-started Implements the ElizaService and registers it with the ConnectRouter. This example shows how to define a service handler for the 'say' RPC method. ```typescript import type { ConnectRouter } from "@connectrpc/connect"; import { ElizaService, SayRequest } from "./gen/connectrpc/eliza/v1/eliza_pb"; export default (router: ConnectRouter) => // registers connectrpc.eliza.v1.ElizaService router.service(ElizaService, { // implements rpc Say async say(req: SayRequest, context: HandlerContext) { return { sentence: `You said: ${req.sentence}` } }, }); ``` -------------------------------- ### CORS Preflight Request Example Source: https://connectrpc.com/docs/cors This example shows a typical OPTIONS request sent by a browser for a CORS preflight check. It includes the origin, requested method, and headers. ```http OPTIONS /connectrpc.greet.v1.GreetService/Greet HTTP/1.1 Origin: https://connectrpc.com Access-Control-Request-Method: POST Access-Control-Request-Headers: Connect-Protocol-Version,Content-Type [other headers elided...] ``` -------------------------------- ### Install mkcert and Generate Local Certificates Source: https://connectrpc.com/docs/node/getting-started These commands are used on macOS with Homebrew to install mkcert and generate TLS certificates for local development. Ensure Node.js can trust these certificates by setting the NODE_EXTRA_CA_CERTS environment variable. ```bash brew install mkcert mkcert -install mkcert localhost 127.0.0.1 ::1 export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem" ``` -------------------------------- ### Plain Function Response Initialization Source: https://connectrpc.com/docs/node/implementing-services This example shows how to define a plain function that returns an initialized response message using `create`. This is one way to implement a service method. ```typescript function say(req: SayRequest) { return create(SayResponseSchema, { sentence: `You said ${req.sentence}` }); } ``` -------------------------------- ### Configure Transport for Connect Protocol Source: https://connectrpc.com/docs/dart/using-clients Example of configuring the Transport for the Connect protocol using ProtoCodec and createHttpClient. Ensure the correct protocol import is uncommented for your use case. ```dart import 'package:connectrpc/http2.dart'; import 'package:connectrpc/connect.dart'; import 'package:connectrpc/protobuf.dart'; import 'package:connectrpc/protocol/connect.dart' as protocol; // import 'package:connectrpc/protocol/grpc.dart' as protocol; // import 'package:connectrpc/protocol/grpc_web.dart' as protocol; final transport = protocol.Transport( baseUrl: "https://demo.connectrpc.com", codec: const ProtoCodec(), // Or JsonCodec() httpClient: createHttpClient(), // statusParser: StatusParser(), // This is required for gRPC and gRPC-Web ); ``` -------------------------------- ### Server Plugin with Context Values Source: https://connectrpc.com/docs/node/interceptors Configure a server plugin (Fastify example) to provide context values for incoming requests. This demonstrates setting the user context from the request object. ```typescript import { fastify } from "fastify"; import { createContextValues } from "@connectrpc/connect"; import { fastifyConnectPlugin } from "@connectrpc/connect-fastify"; import { createValidateInterceptor } from "@connectrpc/validate"; import { kUser } from "./user-context"; import { authenticate } from "./authenticate"; import routes from "./connect"; async function main() { const server = fastify(); await server.register(fastifyConnectPlugin, { // Validation via Protovalidate is almost always recommended interceptors: [createValidateInterceptor()], routes, contextValues: (req) => createContextValues().set(kUser, authenticate(req)), }); await server.listen({ host: "localhost", port: 8080 }); } // You can remove the main() wrapper if you set type: module in your package.json, // and update your tsconfig.json with target: es2017 and module: es2022. void main(); ``` -------------------------------- ### Unary RPC GET Request Example Source: https://connectrpc.com/docs/protocol Example of a unary RPC request using GET for idempotent operations. Parameters like encoding and message are included in the query string. ```http > GET /connectrpc.greet.v1.GreetService/Greet?encoding=json&message=%7B%22name%22%3A%22Buf%22%7D HTTP/1.1 > Host: demo.connectrpc.com ``` -------------------------------- ### Distinguish GET Requests in Handler Source: https://connectrpc.com/docs/node/get-requests-and-caching Introduce behavior specific to HTTP GET requests by checking `context.requestMethod`. This example sets a cache header only for GET requests. ```typescript if (context.requestMethod == "GET") { context.responseHeader.set("Cache-Control", "max-age=604800"); } ``` -------------------------------- ### Create a Basic Mock Transport Source: https://connectrpc.com/docs/web/testing Use `createRouterTransport` to set up an in-memory server with your RPC implementations for mocking backends in component tests. This example demonstrates mocking a simple `say` method. ```typescript import { createRouterTransport } from "@connectrpc/connect"; import { ElizaService } from "@buf/connectrpc_eliza.bufbuild_es/connectrpc/eliza/v1/eliza_pb"; const mockTransport = createRouterTransport(({ service }) => { service(ElizaService, { say: () => { sentence: "I feel happy." }, }); }); ``` -------------------------------- ### Idempotency Level Option in Service Definition Source: https://connectrpc.com/docs/protocol Example of defining an RPC with the 'NO_SIDE_EFFECTS' idempotency level in a service definition. This allows for GET requests. ```protobuf service ElizaService { rpc Say(stream SayRequest) returns (SayResponse) { option idempotency_level = NO_SIDE_EFFECTS; } } ``` -------------------------------- ### Create Proto Directory and File Source: https://connectrpc.com/docs/swift/getting-started Initializes the directory and creates the Protobuf definition file for the ELIZA service. ```bash $ mkdir -p proto && touch proto/eliza.proto ``` -------------------------------- ### RPC Handler Without Context Values Source: https://connectrpc.com/docs/node/interceptors An example of an RPC handler that re-parses the Authorization header to get user information. This approach leads to redundant authentication checks. ```typescript import { ConnectRouter } from "@connectrpc/connect"; import { ElizaService } from "./gen/eliza_pb"; import { authenticate } from "authenticate"; export default (router: ConnectRouter) => // registers connectrpc.eliza.v1.ElizaService router.service(ElizaService, { // implements rpc Say async say(req, context) { const user = authenticate(context.requestHeader.get("Authorization"))!; return { sentence: `Hey ${user.name}! You said: ${req.sentence}`, }; }, }); ``` -------------------------------- ### Create Protobuf Directory and File Source: https://connectrpc.com/docs/dart/getting-started Initializes the directory and file for your Protobuf service definition. ```bash $ mkdir -p proto && touch proto/eliza.proto ``` -------------------------------- ### Enable HTTP GET on Node Client Source: https://connectrpc.com/docs/node/get-requests-and-caching Configure the Connect transport to use HTTP GET for requests by setting `useHttpGet: true`. This is necessary for clients to send GET requests. ```typescript const transport = createConnectTransport({ baseUrl: "https://demo.connectrpc.com", useHttpGet: true, }); const client = createClient(ElizaService, transport); const response = await client.say(request); console.log(response); ``` -------------------------------- ### cURL GET Request Source: https://connectrpc.com/docs/curl-and-other-clients Make a GET request with cURL by encoding the message and encoding type as URL parameters. This method is suitable for clients that prefer or require HTTP GET. ```shell $ curl --get --data-urlencode 'encoding=json' \ --data-urlencode 'message={"sentence": "I feel happy."}' \ https://demo.connectrpc.com/connectrpc.eliza.v1.ElizaService/Say ``` -------------------------------- ### Initialize ElizaApp with ProtocolClient Source: https://connectrpc.com/docs/swift/getting-started Sets up the main application structure with a ProtocolClient configured for the Connect protocol and Protobuf codec. ```swift import Connect import SwiftUI @main struct ElizaApp: App { @State private var client = ProtocolClient( httpClient: URLSessionHTTPClient(), config: ProtocolClientConfig( host: "https://demo.connectrpc.com", networkProtocol: .connect, // Or .grpcWeb codec: ProtoCodec() // Or JSONCodec() ) ) var body: some Scene { WindowGroup { ContentView(viewModel: MessagingViewModel( elizaClient: Connectrpc_Eliza_V1_ElizaServiceClient(client: self.client) )) } } } ``` -------------------------------- ### Fetch API GET Request Source: https://connectrpc.com/docs/curl-and-other-clients Construct a URL with query parameters for encoding and message, then use the fetch API to make an HTTP GET request. This is useful for browser-based clients or when GET is preferred. ```javascript const url = new URL("https://demo.connectrpc.com/connectrpc.eliza.v1.ElizaService/Say"); url.searchParams.set("encoding", "json"); url.searchParams.set("message", JSON.stringify({"sentence": "I feel happy."} )); fetch(url) .then(response => { return response.json() }) .then(data => { console.log(data) }) ``` -------------------------------- ### Generate and Run Go Client for Connect Service Source: https://connectrpc.com/docs/go/getting-started Create a Go client using generated code to interact with the Connect service. This example shows how to set up the client and make a Greet request. ```go package main import ( "context" "log" "net/http" greetv1 "example/gen/greet/v1" "example/gen/greet/v1/greetv1connect" ) func main() { client := greetv1connect.NewGreetServiceClient( http.DefaultClient, "http://localhost:8080", ) res, err := client.Greet( context.Background(), &greetv1.GreetRequest{Name: "Jane"}, ) if err != nil { log.Println(err) return } log.Println(res.Greeting) } ``` ```bash $ go run ./cmd/client/main.go ``` -------------------------------- ### Create Protobuf Directory Structure Source: https://connectrpc.com/docs/python/getting-started Set up the necessary directory structure for your Protocol Buffer files. ```bash $ mkdir -p proto/greet/v1 $ touch proto/greet/v1/greet.proto ``` -------------------------------- ### Initialize Python Project with Connect and Uvicorn Source: https://connectrpc.com/docs/python/getting-started Use 'uv init' to create a new Python project and 'uv add' to install the Connect RPC library and Uvicorn for running ASGI applications. ```bash $ uv init $ uv add connectrpc uvicorn ``` -------------------------------- ### Opting into GET with Idempotency Source: https://connectrpc.com/docs/kotlin/get-requests-and-caching Mark an RPC procedure as side-effect-free using `MethodOptions.IdempotencyLevel.NO_SIDE_EFFECTS` to enable GET requests. ```proto service ElizaService { rpc Say(SayRequest) returns (SayResponse) { option idempotency_level = NO_SIDE_EFFECTS; } } ``` -------------------------------- ### Create Protobuf Service Definition File Source: https://connectrpc.com/docs/node/getting-started Creates the directory structure and an empty Protobuf file for defining the Connect service. ```bash mkdir -p proto/connectrpc/eliza/v1 && touch proto/connectrpc/eliza/v1/eliza.proto ``` -------------------------------- ### Initialize Python Project with Connect and Gunicorn Source: https://connectrpc.com/docs/python/getting-started Use 'uv init' to create a new Python project and 'uv add' to install the Connect RPC library and Gunicorn for running WSGI applications. ```bash $ uv init $ uv add connectrpc gunicorn ``` -------------------------------- ### Connect Protocol Error JSON Example Source: https://connectrpc.com/docs/kotlin/errors This is an example of how an error is represented as JSON on the wire in the Connect protocol. ```http HTTP/1.1 400 Bad Request Content-Type: application/json { "code": "invalid_argument", "message": "sentence cannot be empty" } ``` -------------------------------- ### Initialize Buf Configuration Source: https://connectrpc.com/docs/dart/generating-code Initializes the buf.yaml configuration file for a new project. ```bash $ buf config init ``` -------------------------------- ### Implement ASGI Service Source: https://connectrpc.com/docs/python/getting-started Implement the GreetService for an ASGI server. This example shows how to define an async greet method, access request headers, set response headers, and return a GreetResponse. ```python from connectrpc.request import RequestContext from greet.v1.greet_connect import GreetService, GreetServiceASGIApplication from greet.v1.greet_pb import GreetRequest, GreetResponse class Greeter(GreetService): async def greet(self, request: GreetRequest, ctx: RequestContext[GreetRequest, GreetResponse]) -> GreetResponse: print("Request headers: ", ctx.request_headers()) response = GreetResponse(greeting=f"Hello, {request.name}!") ctx.response_headers()["greet-version"] = "v1" return response app = GreetServiceASGIApplication(Greeter()) ``` -------------------------------- ### Example Connect Error JSON Response Source: https://connectrpc.com/docs/dart/errors This is an example of a JSON response for a Connect error, similar to HTTP status codes. ```json HTTP/1.1 400 Bad Request Content-Type: application/json { "code": "invalid_argument", "message": "sentence cannot be empty" } ``` -------------------------------- ### Enabling GET Requests on Client Configuration Source: https://connectrpc.com/docs/kotlin/get-requests-and-caching Enable HTTP GET requests for your Connect client by setting `getConfiguration` to `GETConfiguration.Enabled` in `ProtocolClientConfig`. ```kotlin val config = ProtocolClientConfig( getConfiguration = GETConfiguration.Enabled, ... ) ``` -------------------------------- ### Initialize ProtocolClient and Service Client Source: https://connectrpc.com/docs/swift/using-clients Demonstrates the initialization of ProtocolClient and a generated service client (Eliza_V1_ElizaServiceClient). This client is typically stored and passed to generated clients. ```swift import Connect // ProtocolClient is usually stored and passed to generated clients. let protocolClient = ProtocolClient( httpClient: URLSessionHTTPClient(), config: ProtocolClientConfig( host: "https://demo.connectrpc.com", // Base URL for APIs networkProtocol: .connect, // Or .grpcWeb codec: ProtoCodec() // Or JSONCodec() ) ) let elizaClient = Eliza_V1_ElizaServiceClient(client: protocolClient) ``` -------------------------------- ### Unary RPC POST Response Example Source: https://connectrpc.com/docs/protocol Example of a successful unary RPC response with JSON payload. The Content-Type indicates the response format. ```http < HTTP/1.1 200 OK < Content-Type: application/json < < {"greeting": "Hello, Buf!"} ``` -------------------------------- ### Unary-Response: Simple JSON Request and Response (GET) Source: https://connectrpc.com/docs/protocol Illustrates a unary RPC using a GET request with URL-encoded parameters and a successful JSON response. ```http > GET /connectrpc.greet.v1.GreetService/Greet?message=%7B%22name%22%3A%22Buf%22%7D&encoding=json&connect=v1 HTTP/1.1 > Host: demo.connectrpc.com < HTTP/1.1 200 OK < Content-Type: application/json < < {"greeting": "Hello, Buf!"} ``` -------------------------------- ### Unary RPC POST Request Example Source: https://connectrpc.com/docs/protocol Example of a unary RPC request using POST with JSON payload. Ensure the Content-Type is set to application/json. ```http > POST /connectrpc.greet.v1.GreetService/Greet HTTP/1.1 > Host: demo.connectrpc.com > Content-Type: application/json > > {"name": "Buf"} ``` -------------------------------- ### Set up Connect Client in React App Source: https://connectrpc.com/docs/web/getting-started Import necessary functions and service definitions to create a Connect client. Configure the transport with the base URL of the service and then combine the service definition with the transport to instantiate the client. ```typescript import { createClient } from "@connectrpc/connect"; import { createConnectTransport } from "@connectrpc/connect-web"; // Import service definition that you want to connect to. import { ElizaService } from "@buf/connectrpc_eliza.bufbuild_es/connectrpc/eliza/v1/eliza_pb"; // The transport defines what type of endpoint we're hitting. // In our example we'll be communicating with a Connect endpoint. // If your endpoint only supports gRPC-web, make sure to use // `createGrpcWebTransport` instead. const transport = createConnectTransport({ baseUrl: "https://demo.connectrpc.com", }); // Here we make the client itself, combining the service // definition with the transport. const client = createClient(ElizaService, transport); ``` -------------------------------- ### Making Sync GET Requests with Connect Client Source: https://connectrpc.com/docs/python/get-requests-and-caching Use the `use_get=True` parameter when calling sync methods marked as side-effect free to leverage HTTP GET. ```python response = client.say(SayRequest(sentence="Hello"), use_get=True) ``` -------------------------------- ### Making Async GET Requests with Connect Client Source: https://connectrpc.com/docs/python/get-requests-and-caching Use the `use_get=True` parameter when calling async methods marked as side-effect free to leverage HTTP GET. ```python response = await client.say(SayRequest(sentence="Hello"), use_get=True) ``` -------------------------------- ### Test Greet Service with unittest (ASGI) Source: https://connectrpc.com/docs/python/testing Tests the Greet service using unittest with an in-memory ASGI transport. This example demonstrates running an async test within a synchronous unittest method. ```python import asyncio import unittest from pyqwest import Client from pyqwest.testing import ASGITransport from greet.v1.greet_connect import GreetServiceASGIApplication, GreetServiceClient from greet.v1.greet_pb import GreetRequest from server import Greeter class TestGreet(unittest.TestCase): def test_greet(self): async def run_test(): app = GreetServiceASGIApplication(Greeter()) client = GreetServiceClient( "http://test", http_client=Client(ASGITransport(app)) ) response = await client.greet(GreetRequest(name="Alice")) self.assertEqual(response.greeting, "Hello, Alice!") asyncio.run(run_test()) ``` -------------------------------- ### Implement WSGI Service Source: https://connectrpc.com/docs/python/getting-started Implement the GreetServiceSync for a WSGI server. This example shows how to define a synchronous greet method, access request headers, set response headers, and return a GreetResponse. ```python from greet.v1.greet_connect import GreetServiceSync, GreetServiceWSGIApplication from greet.v1.greet_pb import GreetResponse class Greeter(GreetServiceSync): def greet(self, request, ctx): print("Request headers: ", ctx.request_headers()) response = GreetResponse(greeting=f"Hello, {request.name}!") ctx.response_headers()["greet-version"] = "v1" return response app = GreetServiceWSGIApplication(Greeter()) ``` -------------------------------- ### Client Streaming RPC Response Example Source: https://connectrpc.com/docs/protocol Example of a client streaming RPC response. It includes the final result and an error/trailers indicator, both prefixed with binary framing. ```http < HTTP/1.1 200 OK < Content-Type: application/connect+json < < {"greeting": "Hello, Buf and Connect!"} < {} ``` -------------------------------- ### Client: Set Request Headers and Read Response Headers Source: https://connectrpc.com/docs/go/headers-and-trailers On the client, use `NewClientContext` to create a context with header access. Set request headers before the call and read response headers after. ```go func main() { client := greetv1connect.NewGreetServiceClient( http.DefaultClient, "http://localhost:8080", ) ctx, callInfo := connect.NewClientContext(context.Background()) callInfo.RequestHeader().Set("Acme-Tenant-Id", "1234") _, err := client.Greet(ctx, &greetv1.GreetRequest{ Name: "Jane", }) if err != nil { fmt.Println(err) return } fmt.Println(callInfo.ResponseHeader().Get("Greet-Version")) } ``` -------------------------------- ### Create Protobuf Directory Source: https://connectrpc.com/docs/kotlin/getting-started Create the necessary directory structure for your Protobuf schema files. ```bash mkdir -p proto/connectrpc/eliza/v1 touch proto/connectrpc/eliza/v1/eliza.proto ``` -------------------------------- ### Opt-in to NO_SIDE_EFFECTS for GET Requests Source: https://connectrpc.com/docs/go/get-requests-and-caching Mark a service procedure as side-effect free using the `idempotency_level` option to enable GET requests. This requires Connect Go v1.7.0 or newer. ```proto service GreetService { rpc Greet(GreetRequest) returns (GreetResponse) { option idempotency_level = NO_SIDE_EFFECTS; } } ``` -------------------------------- ### Client Streaming RPC POST Request Example Source: https://connectrpc.com/docs/protocol Example of a client streaming RPC request using POST with JSON payload. Each message is prefixed with binary framing data. ```http > POST /connectrpc.greet.v1.GreetService/GreetGroup HTTP/1.1 > Host: demo.connectrpc.com > Content-Type: application/connect+json > > {"name": "Buf"} > {"name": "Connect"} ``` -------------------------------- ### Calling a Connect Demo Service with cURL Source: https://connectrpc.com/docs/introduction This example demonstrates how to call the Connect RPC demo service using cURL with JSON encoding. Ensure the Content-Type header is set correctly. ```bash curl \ --header "Content-Type: application/json" \ --data '{"sentence": "I feel happy."}' \ https://demo.connectrpc.com/connectrpc.eliza.v1.ElizaService/Say ``` -------------------------------- ### CORS Preflight Response Example Source: https://connectrpc.com/docs/cors This example demonstrates a successful CORS preflight response. It allows requests from a specific origin, specifies allowed methods and headers, and sets caching parameters. ```http HTTP/1.1 204 No Content Access-Control-Allow-Origin: https://connectrpc.com Access-Control-Allow-Methods: POST,GET Access-Control-Allow-Headers: Content-Type,Connect-Protocol-Version,Connect-Timeout-Ms,Grpc-Timeout,X-Grpc-Web,X-User-Agent Access-Control-Max-Age: 7200 Vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers [other headers elided...] ``` -------------------------------- ### Create gRPC Client with connect-go Source: https://connectrpc.com/docs/go/getting-started Use the `WithGRPC` option when creating a `GreetServiceClient` to enable communication over the gRPC protocol. This is useful for interop with other gRPC services. ```go client := greetv1connect.NewGreetServiceClient( http.DefaultClient, "http://localhost:8080", connect.WithGRPC(), ) ``` -------------------------------- ### Conditionally Set Cache Header for GET Requests Source: https://connectrpc.com/docs/go/get-requests-and-caching In a Connect handler, check if the incoming request is an HTTP GET request using `callInfo.HTTPMethod()`. If it is, you can set specific caching headers like `Cache-Control`. ```go callInfo, ok := connect.CallInfoForHandlerContext(ctx) if ok && callInfo.HTTPMethod() == http.MethodGet { callInfo.ResponseHeader().Set("Cache-Control", "max-age=604800") } ``` -------------------------------- ### Initialize Connect RPC Client Source: https://connectrpc.com/docs/dart/using-clients Sets up the transport and client for making RPC calls. Ensure the baseUrl and codec are configured correctly for your service. ```dart import './gen/eliza.pb.dart'; import './gen/eliza.connect.client.dart'; import 'package:connectrpc/http2.dart'; import 'package:connectrpc/connect.dart'; import 'package:connectrpc/protobuf.dart'; import 'package:connectrpc/protocol/connect.dart' as protocol; final transport = protocol.Transport( baseUrl: "https://demo.connectrpc.com", codec: const ProtoCodec(), // Or JsonCodec() httpClient: createHttpClient(), ); final elizaClient = ElizaServiceClient(transport); ``` -------------------------------- ### Enable HTTP GET on Connect Go Client Source: https://connectrpc.com/docs/go/get-requests-and-caching When creating a Connect client in Go, use the `connect.WithHTTPGet()` option to enable GET requests for eligible procedures. Ensure your client is configured with a recent Connect Go version. ```go client := greetv1connect.NewGreetServiceClient( http.DefaultClient, "http://localhost:8080", connect.WithHTTPGet(), ) ```