Skip to content

Instantly share code, notes, and snippets.

@hapaxlife
Last active March 4, 2024 01:41
Show Gist options
  • Save hapaxlife/28a850531775dd61365b360e82a500c6 to your computer and use it in GitHub Desktop.
Save hapaxlife/28a850531775dd61365b360e82a500c6 to your computer and use it in GitHub Desktop.
Deno, Hono, Zod Open API, Swagger UI

Deno, Hono, Zod Open API, Swagger UI

See :

Script

Run deno run -A --allow-env --unstable --watch server.ts

Result

API

Scheme for OPEN API

Swagger UI (use scheme at /doc)

Scalar UI (use scheme at /doc)

export { Hono } from "https://deno.land/x/hono@v3.12.6/mod.ts";
export { createRoute, OpenAPIHono, z } from "npm:@hono/zod-openapi";
export { swaggerUI } from "npm:@hono/swagger-ui";
export { apiReference } from 'npm:@scalar/hono-api-reference'
import { z, createRoute, OpenAPIHono, swaggerUI, apiReference } from './deps.ts'
const ParamsSchema = z.object({
id: z
.string()
.min(3)
.openapi({
param: {
name: 'id',
in: 'path',
},
example: '1212121',
}),
})
const UserSchema = z
.object({
id: z.string().openapi({
example: '123',
}),
name: z.string().openapi({
example: 'John Doe',
}),
age: z.number().openapi({
example: 42,
}),
})
.openapi('User')
const ErrorSchema = z.object({
code: z.number().openapi({
example: 400,
}),
message: z.string().openapi({
example: 'Bad Request',
}),
})
const route = createRoute({
method: 'get',
path: '/users/{id}',
request: {
params: ParamsSchema,
},
responses: {
200: {
content: {
'application/json': {
schema: UserSchema,
},
},
description: 'Retrieve the user',
},
400: {
content: {
'application/json': {
schema: ErrorSchema,
},
},
description: 'Returns an error',
},
},
})
const app = new OpenAPIHono()
app.openapi(route, (c) => {
const { id } = c.req.valid('param')
return c.json({
id,
age: 20,
name: 'Ultra-man',
})
})
// The OpenAPI documentation will be available at /doc
app.doc('/doc', {
openapi: '3.1.0', // 3.0.0
info: {
version: '1.0.0',
title: 'My API',
},
})
// Use Scalar
app.get(
'/reference',
apiReference({
spec: {
url: '/doc',
},
}),
)
// OR Use the middleware to serve Swagger UI at /ui
app.get('/ui', swaggerUI({ url: '/doc' }))
Deno.serve(app.fetch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment