Skip to main content

HTTP/REST

HTTP Runtime

The HTTPRuntime allows your typegraphs to access external REST APIs.

Common use cases (but not limited to):

  • Enable consuming one or more REST APIs through the same interface
  • Programmatically generate typegraphs from an existing openapi specs or similar

Example:

http-runtime.ts ↗
import { HttpRuntime } from "@typegraph/sdk/runtimes/http";

await typegraph(
{
name: "http-runtime",
},
(g) => {
const facts = new HttpRuntime("https://uselessfacts.jsph.pl/api/v2/facts");
const pub = Policy.public();

g.expose(
{
facts: facts.get(
t.struct({
language: t.enum_(["en", "de"]),
}),
t.struct({
id: t.string(),
text: t.string(),
source: t.string(),
source_url: t.string(),
language: t.string(),
permalink: t.string(),
}),
{
path: "/random",
},
),
facts_as_text: facts.get(
t.struct({
header_accept: t.string().set("text/plain"),
language: t.enum_(["en", "de"]),
}),
t.string(),
{ path: "/random", headerPrefix: "header_" },
),
},
pub,
);
},
);
Variables
Headers

Verbs

This runtime supports GET, POST, PUT, DELETE http verbs.

In most cases, queries are not limited to a simple query parameter or use the default application/json content type. You can assign what parts of your request description each field in the input struct belongs to.

In the example bellow, this endpoint corresponds to POST <API_URL>/submit_user?form_type=.. with a body requiring the fields: pseudo, age and with header accept set as application/json.

// ..
const remote = new HttpRuntime("<API_URL>");
g.expose({
add_user: remote.post(
// define your input/output
t.struct(
{
id: t.uuid(),
username: t.float(),
years_lived: t.integer(),
form_type: t.integer()
},
),
t.struct({ message: t.string() }),
{
path: "/submit_user",
// specify where each field in your input should be associated with
bodyFields: ["username", "years_lived"],
queryFields: ["form_type"],
// you may want to rename a few fields
// if you are using your own naming conventions or reusing types
renameFields: [
["username", "pseudo"],
["years_lived", "age"],
],
contentType: "multipart/form-data",
}
)}, pub);
// ..
Feedback