Tutorials

Tutorials

Talking to an OpenAPI-Described Service

If a service publishes an OpenAPI (Swagger) document, GPAL.RESTClient can load it directly and discover its endpoints for you. This short tutorial loads a spec, lists its endpoints, calls one, and pretty-prints the JSON response with GPAL.Converter.

Complete Program

Here's the whole workflow, start to finish. Each piece is broken down and explained below.

using GenerallyPositive;

GPAL.WithPublishToConsole();

IRESTClient restClient = GPAL.RESTClient

.LoadOpenAPIMap("https://example.com/openapi/basicstore-api-v2.yaml")

.ListOpenAPIEndPoints()

.ToGPALObject();

string data = restClient.WithEndpoint("/api/basicstore/products").Execute();

string pretty;

GPAL.Converter.WithInput(data).PrettyPrintTo(out pretty);

Console.WriteLine(pretty);

data = restClient.WithEndpoint("/api/basicstore/products").WithHttpMethod("OPTIONS").Execute();

GPAL.Converter.WithInput(data).PrettyPrintTo(out pretty);

Console.WriteLine(pretty);

Load the Spec and Discover Endpoints

LoadOpenAPIMap points GPAL.RESTClient at a YAML or JSON OpenAPI document - it reads the document and learns the service's base URL and available paths. ListOpenAPIEndPoints prints those discovered endpoints to your configured loggers, which is a quick way to confirm the spec loaded correctly before you start calling it.

IRESTClient restClient = GPAL.RESTClient

.LoadOpenAPIMap("https://example.com/openapi/basicstore-api-v2.yaml")

.ListOpenAPIEndPoints()

.ToGPALObject();

TIP

Calling ListOpenAPIEndPoints is optional - it's there so you can see, in your console or log output, exactly which endpoint paths the loaded spec exposes before wiring them into your workflow.

Call an Endpoint by Path

Once the client has a spec loaded, WithEndpoint takes the same path strings ListOpenAPIEndPoints printed. Execute() sends the request and returns the raw response body as a string - here, a JSON product list.

string data = restClient.WithEndpoint("/api/basicstore/products").Execute();

Pretty-Print the Response and Try Other Methods

GPAL.Converter.WithInput(data).PrettyPrintTo(out pretty) reformats the raw JSON string for readable console output. WithHttpMethod lets you override the verb for the same endpoint - here OPTIONS instead of the default GET - useful for checking what a service allows before you call it.

GPAL.Converter.WithInput(data).PrettyPrintTo(out pretty);

Console.WriteLine(pretty);

data = restClient.WithEndpoint("/api/basicstore/products").WithHttpMethod("OPTIONS").Execute();

GPAL.Converter.WithInput(data).PrettyPrintTo(out pretty);

Console.WriteLine(pretty);

TIP

GPAL.Converter isn't tied to REST responses - PrettyPrintTo and its siblings work on any JSON or XML string you hand it. See GPALConverter: Converting Between Formats.