r/coolgithubprojects • • 19m ago

Tspgen: Generate Rest client sdk and server stub from a shared codebase

https://github.com/AbhigyaKrishna/tspgen

Hey all, I've been working on tspgen, a set of TypeSpec emitters. You describe your API once in TypeSpec, and it generates models, server stubs and typed client SDKs from that.

While working on some my own projects, I got tired of managing the rest api definitions and syncing the client and server whenever there were changes. The server has one idea of the contract, the client has another, and the docs have a third. I wanted a single source of truth, with everything else generated from it, and I wanted the generated code to be something I'd actually be happy to read and maintain.

The main features are worked on are:

  • One source of truth. The API lives in a single TypeSpec file. Server and client are generated from the same internal representation, so they can't disagree about the contract. The server stub generates only the required route definitions and REST controllers, leaving business logic to be implemented separately.
  • Extendable. The core is language-neutral. Languages and frameworks are separate packages on a plugin API, so adding a new target doesn't mean touching the core. Defining custom generation logic for your apps is as easy as adding a single typescript plugin file and some eta templates.
  • Adaptable. Templates, naming and output layout are customizable, so the generator fits your codebase instead of forcing you to fit it. Right now it covers Kotlin (Ktor), TypeScript (Next.js, Express), Go (net/http, Gin), Python (FastAPI, Django), Java (Spring, JAX-RS), and Rust (Axum, Actix).
  • Quality generated code. The goal is idiomatic output per language, not lowest-common-denominator templates. It's backed by cross-language e2e tests that run generated clients against generated servers over real HTTP, plus a security and correctness audit pass.

Repo: https://github.com/AbhigyaKrishna/tspgen

Example:

import "@typespec/http";
using Http;

@service(#{ title: "Pet Store" })
@useAuth(BearerAuth)
namespace PetStore;

enum Species { dog, cat, bird: "parrot" }

model Pet {
  id: int64;
  @minLength(1) name: string;
  species: Species;
  @encodedName("application/json", "born_at") bornAt?: utcDateTime;
}

model PetPage {
  @pageItems items: Pet[];
  @continuationToken nextToken?: string;
}

@error model NotFound { @statusCode _: 404; message: string; }

@route("/pets")
interface Pets {
  @list @get list(@query @continuationToken token?: string, @query @pageSize limit?: int32): PetPage;
  @get read(@path id: int64): Pet | NotFound;
  @post create(@body pet: Pet): { @statusCode _: 201; @body body: Pet };
}

Generated ts client:

const api = createPetStoreClient({
  baseUrl: process.env.API_BASE_URL!,
  auth: { BearerAuth: () => getToken() },
});

const pet = await api.pets.read({ id: 1 }, { next: { revalidate: 60, tags: ["pets"] } });
for await (const item of api.pets.listItems({ limit: 50 })) {
  console.log(item.name, item.bornAt);
}

// React Client Component — generated TanStack Query hooks & keys
const { data } = usePetsReadQuery({ id: 1 });
const create = usePetsCreateMutation({
  onSuccess: () => queryClient.invalidateQueries({ queryKey: petStoreKeys.pets.all }),
});

I'd love feedback from fellow developers on what to support next.

1 Upvotes

0 comments sorted by