Generate a client and a server

This guide generates both sides of an API from its OpenAPI document, openapi.yaml: a TypeScript client for the Fetch API and an Express server, then the same pair in Java, Go, Python, C# and Elixir. The steps work for the other targets of apigenie-generator too, and for AsyncAPI, GraphQL and Protobuf documents.

You need the CLI installed; the Quickstart shows how. Lint the document first (Lint and format API descriptions): a clean contract gives cleaner code.

Generate the client

apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client

The output is an npm package with no runtime dependencies: requests go through the global fetch(), so the client runs in browsers and in Node.js 18 or later. Each operation is an async function named after its operationId, with its parameters and its result typed from the document:

import { configure, ApiError, listShipments, getShipment } from "shipping-client";

configure({
  baseUrl: "https://api.example.com/v2",
  auth: { apiKey: "ce_live_123" },
});

try {
  const page = await listShipments({ status: ["in_transit"], limit: 20 });
  const shipment = await getShipment({ shipmentId: "shp_01J9Z" });
} catch (error) {
  if (error instanceof ApiError) {
    console.error(error.status, error.body);
  }
}

To compile the client as part of your own project instead of as a package, set layout: sources for client_fetch in the configuration (see Configure the generators below): the generator then writes only the sources.

Generate the server

apigenie-generator server express openapi.yaml -o server --package-name shipping-server

The generator writes typed handler interfaces and a router that decodes and validates every request. Your code implements the handlers in files of its own, so regenerating never overwrites it:

import express from "express";
import { BASE_PATH, createRouter, HttpError, type ShipmentsHandlers } from "shipping-server";

const shipments: Partial<ShipmentsHandlers> = {
  async getShipment(request) {
    const shipment = await db.shipments.find(request.params.shipmentId);
    if (shipment === undefined) {
      throw new HttpError(404, "No such shipment");
    }
    return { status: 200, body: shipment };
  },
};

const app = express();
app.use(BASE_PATH, createRouter({ shipments }));
app.listen(8080);

Operations are grouped by their first tag (ShipmentsHandlers), and the status, body and headers a handler returns are typed per status from the document. A change to the contract that the handlers don’t follow is a compile error.

Start in your language

Every language has the same pair: a client that needs the language’s usual toolchain and little else, and a server that validates every request and leaves the implementation to files it never overwrites. The commands below generate from the same openapi.yaml, whose title is Shipping API, whose operations are tagged shipments, and whose security scheme is an API key named apiKey; --package-name names the package where the language has one. Each target’s page lists its options and what it generates.

Java

apigenie-generator client java openapi.yaml -o client-java --package-name shipping
apigenie-generator server spring openapi.yaml -o server-java --package-name shipping

The client is a Maven project for Java 17 or later, with ApiClient on Spring’s RestClient (--library picks resttemplate, feign or http-interface instead) and one class per tag:

ApiClient client = new ApiClient();
client.setBasePath("https://api.example.com/v2");
client.setApiKey("ce_live_123");
ShipmentsApi shipments = new ShipmentsApi(client);

Shipment shipment = shipments.getShipment("shp_01J9Z");
ResponseEntity<List<Shipment>> page = shipments.listShipmentsWithHttpInfo(List.of(ShipmentStatus.IN_TRANSIT), 20);

The server is a Spring Boot 3 project with the layout and the options of openapi-generator’s spring generator: an interface per tag (ShipmentsApi) and a controller implementing it (ShipmentsApiController), which is written only when it is missing, so the implementation goes there and survives regeneration. See client java and server spring.

Go

apigenie-generator client go openapi.yaml -o client-go --package-name shipping
apigenie-generator server go openapi.yaml -o server-go --package-name shipping -p layout=module

Both use the standard library only. The client has a NewClient with an option per server and security scheme, and a method per operation whose response has a typed field per status and media type:

client, err := shipping.NewClient(
    shipping.WithBaseURL("https://api.example.com/v2"),
    shipping.WithAPIKey(os.Getenv("API_KEY")),
)
if err != nil {
    return err
}
res, err := client.GetShipment(ctx, "shp_01J9Z")
if err != nil {
    return err
}
fmt.Println(res.JSON200.Status)

The server follows oapi-codegen’s names: implement ServerInterface, whose methods get the bound and validated parameters, or StrictServerInterface, whose methods return typed responses such as GetShipment200JSONResponse, and mount it with HandlerWithOptions on an http.ServeMux. -p layout=module writes a go.mod; without it the output is a package of your module. See client go and server go.

Python

apigenie-generator client python openapi.yaml -o client-python --package-name shipping_client
apigenie-generator server fastapi openapi.yaml -o server-python --package-name shipping

The client needs Python 3.10 or later, pydantic 2.11 or later and httpx, and has a resource per tag with a method per operation, on Client and on AsyncClient:

from shipping_client import Client, NotFoundError

with Client(api_key="ce_live_123") as client:
    page = client.shipments.list_shipments(status=["in_transit"], limit=20)
    try:
        shipment = client.shipments.get_shipment("shp_01J9Z")
    except NotFoundError as error:
        print(error.body)

The server has the layout and the options of openapi-generator’s python-fastapi generator, for FastAPI 0.115 or later: the routes validate the requests and call the methods of BaseShipmentsApi, which answer 501 until a subclass in the impl package implements them. uvicorn shipping.main:app --reload --port 8080 runs it. See client python and server fastapi.

C#

apigenie-generator client csharp openapi.yaml -o client-csharp
apigenie-generator server aspnet openapi.yaml -o server-csharp

The names come from the document’s title: the client is a net8.0 class library in the Shipping.Client namespace, referencing only Microsoft.Extensions.Http, with a typed client per tag registered for dependency injection:

services.AddShippingClient(options =>
{
    options.BaseUrl = new Uri("https://api.example.com/v2");
    options.ApiKey = ApiCredential.Static(configuration["Shipping:ApiKey"]!);
});

// inject ShippingClient, or the client of a tag, IShipmentsClient
var shipment = await client.Shipments.GetShipmentAsync("shp_01J9Z", cancellationToken);

The server targets .NET 8 with the shared framework alone: an interface per tag (IShipmentsApi) whose methods return the declared responses as Results<Ok<Shipment>, ...>, so the compiler accepts only those, its implementation in Apis/ShipmentsApi.cs and the host in Program.cs, both written only when missing, and app.MapShippingApi() to map the endpoints. dotnet run starts it. See client csharp and server aspnet.

Elixir

apigenie-generator client elixir openapi.yaml -o client-elixir --package-name shipping
apigenie-generator server phoenix openapi.yaml -o server-elixir --package-name shipping

Both are Mix projects for Elixir 1.18 or later. The client depends on Req, and has a module per tag with a function per operation, returning {:ok, value} or {:error, error}, and a ! variant that raises:

client = Shipping.new(base_url: "https://api.example.com/v2", auth: [api_key: "ce_live_123"])

{:ok, shipment} = Shipping.Api.Shipments.get_shipment(client, shipment_id: "shp_01J9Z")
shipment = Shipping.Api.Shipments.get_shipment!(client, shipment_id: "shp_01J9Z")

The server is a Phoenix 1.7 application whose router matches the operations, checks the credentials and decodes the parameters and bodies before calling a behaviour per tag, ShippingWeb.Api.Shipments. Implement it in a module of your own, name that module in config/config.exs (config :shipping, ShippingWeb.Api.Shipments, impl: MyApp.Shipments), and run mix phx.server; operations without an implementation answer 501. See client elixir and server phoenix.

Configure the generators

Generator settings go in the commands.generate section of apigenie.yaml, one entry per target, so the command lines stay short and the settings are reviewed like code (how the file is found and read). Here the client’s imports suit a bundler, and an overlay adjusts the document for the server:

version: '1.0'
commands:
  generate:
    client_fetch:
      import_extension: ''
    server_express:
      overlay:
        - overlays/express.overlay.yaml

Each target’s page lists its settings and the vendor extensions it reads, such as client fetch and server express. Extensions that matter to one generator only can live in an OpenAPI Overlay of that generator, listed under overlay or given with --overlay, instead of in the API description.

Check the generated code in CI

Generate into the repository and commit the output with the description, so that reviewers see the change to the API and its effect on the code in the same diff. Give every option on the command line or in apigenie.yaml, so that CI runs exactly what you run. Then let every pull request check that the generated files still match the description. --check runs the generator without writing anything, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0).

After a value is added to an enum of the document, for example a t unit in the Weight schema of the Carpet Express document, the check fails until you regenerate:

apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client --check
client/src/types.ts
1 generated file(s) would change and 0 would be created.

Run the same command without --check, review the diff and commit it. When the generated code is up to date, --check lists no file and exits with 0. Files a target writes only when they are missing, such as the README.md of server express, belong to you once they exist. --check leaves them out. Files the generator doesn’t write at all are not compared either, so a file left behind by a removed operation stays until you delete it.

On GitHub, the API Genie Action without a command installs the CLI and puts apigenie-generator on the PATH. A step after it runs the check for each target and fails the job when any of them finds a difference:

on: pull_request
jobs:
  generated:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: mykulyak/api-genie-action@v0
        with:
          version: 0.12.0
      - name: Generated code matches the API description
        run: |
          status=0
          apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client --check || status=1
          apigenie-generator server express openapi.yaml -o server --package-name shipping-server --check || status=1
          exit $status

The generated files hold no date and no path of your machine, so the check gives the same result on any Linux or macOS runner. A new generator version can change them: pin the version in CI and in your package manager, and regenerate in the pull request that upgrades it. Other CI systems run the same commands once the CLI is installed (Installing the CLI in a job); the npm package installs apigenie-generator next to apigenie.

Once the server runs, check that it keeps the contract with a validating proxy: Mock and contract-test an API.

Next steps

Was this helpful?