npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cloudflare/itty-router-openapi

v1.1.1

Published

OpenAPI schema generator and validator for Cloudflare Workers

Downloads

20,610

Readme

itty-router-openapi


Documentation: https://cloudflare.github.io/itty-router-openapi/

Source Code: https://github.com/cloudflare/itty-router-openapi/


itty-router-openapi is a library that extends itty-router, a powerful and lightweight routing system for Cloudflare Workers, already familiar to many developers, and adds an easy-to-use and compact OpenAPI 3 and 3.1 schema generator and validator.

itty-route-openapi can also have class-based routes, allowing the developer to quickly build on top of and extend other endpoints while reusing code.

The key features are:

A template repository is available at cloudflare/workers-sdk, with a live demo here.

Why create another router library for workers?

This framework built on top of itty-router and extends some of its core features, such as adding class-based endpoints. It also provides a simple and iterative path for migrating from old applications based on itty-router.

Building APIs and maintaining good documentation on the parameters and fields of your API hard. However, there is an open standard that makes this documentation process much more effortless, called OpenAPI.

OpenAPI "defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection." This allows other machines to reliably parse those definitions and use the remote APIs easily, without additional implementation logic.

Some of the top requirements for Radar 2.0 were having better API documentation, improving the deployment lifecycle with end-to-end testing, and making it publicly available to Cloudflare customers. OpenAPI support quickly jumped out as the obvious choice to help us on all these fronts.

However, we struggled to find an existing OpenAPI framework that checked all our boxes:

  • Easy integration with Cloudflare Workers
  • Input validation for endpoints parameters
  • Actual code-based schema generation (not just generated from comments or manually)

Since we couldn't find anything that suited us, as many engineers do, we opted for the second-best alternative: building our own and open-source it.

Quick setup

Get started fast using the create-cloudflare command line, just run this command to setup an initial project with some example routes:

npm create cloudflare@latest hello-world -- --type openapi

---> 100%

Then to start the local server just run

cd hello-world
wrangler dev

Installation

npm i @cloudflare/itty-router-openapi --save

---> 100%

Example

Let's create our first class-based endpoint called TaskFetch in src/tasks.ts now.

Make sure that ‘Task' is global, otherwise you must redefine responses.schema.task with every endpoint.

When defining the schema, you can interchangeably use native typescript types or use the included types to set required flags, descriptions, and other fields.

import {
  OpenAPIRoute,
  Path,
  Str,
  DateOnly,
  DataOf,
} from '@cloudflare/itty-router-openapi'

const Task = {
  name: new Str({ example: 'lorem' }),
  slug: String,
  description: new Str({ required: false }),
  completed: Boolean,
  due_date: new DateOnly(),
}

export class TaskFetch extends OpenAPIRoute {
  static schema = {
    tags: ['Tasks'],
    summary: 'Get a single Task by slug',
    parameters: {
      taskSlug: Path(Str, {
        description: 'Task slug',
      }),
    },
    responses: {
      '200': {
        description: 'Task fetched successfully',
        schema: {
          metaData: {},
          task: Task,
        },
      },
    },
  }

  async handle(
    request: Request,
    env: any,
    context: any,
    data: DataOf<typeof TaskFetch.schema>
  ) {
    // Retrieve the validated slug
    const { taskSlug } = data.params

    // Actually fetch a task using the taskSlug

    return {
      metaData: { meta: 'data' },
      task: {
        name: 'my task',
        slug: taskSlug,
        description: 'this needs to be done',
        completed: false,
        due_date: new Date().toISOString().slice(0, 10),
      },
    }
  }
}

Now initialize a new OpenAPIRouter, and reference our newly created endpoint as a regular ‘itty-router’ .get route:

import { OpenAPIRouter } from '@cloudflare/itty-router-openapi'
import { TaskFetch } from './tasks'

const router = OpenAPIRouter()
router.get('/api/tasks/:taskSlug/', TaskFetch)

// 404 for everything else
router.all('*', () => new Response('Not Found.', { status: 404 }))

export default {
  fetch: router.handle,
}

Finally, run wrangler dev and head to /docs our /redocs with your browser.

You'll be greeted with a beautiful OpenAPI page that you can use to test and call your new endpoint.

Tutorial Example Preview

Pretty easy, right?

Feedback and contributions

itty-router-openapi aims to be at the core of new APIs built using Workers and define a pattern to allow everyone to have an OpenAPI-compliant schema without worrying about implementation details or reinventing the wheel.

itty-router-openapi is considered stable and production ready and is being used with the Radar 2.0 public API.

Currently this package is maintained by the Cloudflare Radar Team and features are prioritized based on the Radar roadmap.

Nonetheless you can still open pull requests or issues in this repository and they will get reviewed.

You can also talk to us in the Cloudflare Community or the Radar Discord Channel