DEV Community

Cover image for HONC Out Loud: The Modern Guide to Building a Typescript JSON API
Nele Lea for Fiberplane

Posted on • Updated on

HONC Out Loud: The Modern Guide to Building a Typescript JSON API

Building a simple API today involves many choices. We can easily spend more time considering the tools to build and run the API than focusing on the API's business logic itself. Naturally, we need to evaluate the requirements our data API should fulfill and choose components accordingly. In my case, I want something that runs in the cloud, scales as needed, and ideally only runs when required. However, I don't want to deal with Kubernetes or rely on one of the big cloud vendors. Fortunately, several tools are available for deploying serverless functions, such as Netlify Functions, Cloudflare Workers, Vercel Serverless Functions, Supabase Edge Functions, and Deno Deploy. Welcome to the jungle of endless possibilities.

We've only just started venturing into this jungle, as different cloud platforms support different JavaScript runtimes, and different runtimes come with their own frameworks. One framework that stands out in this jungle is Hono. Hono is runtime-independent, making it a good starting point because the same code can run on multiple platforms. This facilitates easier migration and establishes a standard for JavaScript web development across platforms.

HONC Introduction

In addition to the web framework, you still need to decide on other components. HONC is an opinionated stack focusing on Hono as the web framework, Drizzle as the ORM, Neon as the database, and Cloudflare Workers for deployment. While these components are interchangeable, the HONC template is designed to help you set things up quickly by providing a consistent and opinionated structure. Here is a brief introduction to the individual components of HONC:

Hono

Hono is a web application framework that supports any JavaScript runtime, including Cloudflare, Deno, Bun, Vercel, Netlify, Node.js, and more. The RegExpRouter makes it super fast by avoiding any linear loops. Additionally, it is lightweight (14kB) and uses only the Web Standard API, meaning there are no dependencies. Developers can use built-in middleware or create their own to extend the framework.

ORM (Drizzle)

Drizzle is a headless Object Relational Mapper (ORM) that maps the data logic in the database with the application code. Drizzle offers both a relational and an SQL-like query API, providing an interface that closely resembles SQL, ensuring a good developer experience without the need to learn library-specific APIs. It has zero dependencies, is dialect-specific, performant, and serverless by design.

Neon (Database)

Neon provides a serverless PostgreSQL database that supports branching. It is an open-source alternative to AWS Aurora and Google Cloud SQL for PostgreSQL. You can run Neon on-premise or use their managed service in the cloud. Neon separates compute and storage, allowing it to offer features like auto-scaling and branching.

Cloud(flare Workers)

Cloudflare is a global cloud platform. Workers are serverless applications running on JavaScript edge runtime on globale cloudflare CDN. Cloudflare Workers allow the creation of applications without configuring or maintaining infrastructure. With a focus on shipping serverless applications instantly and its isolate architecture, Cloudflare Workers provide a seamless and performant solution for running application code.

Getting started with HONC

There are multiple ways to get started with HONC. You can set up all the components manually, but there is also a create-honc-app cli available as npm package helping to create a new HONC project from your Shell. Simply type: npm create honc-app@latest

You can choose between a sample API template and a bare template. The sample API template comes with some business logic and implements a Goose quotes API. It allows to inspect the individual components of the stack. The bare template creates the HONC project structure and allows to get started quickly with implementing own business logic.

Next, we'll explore the Goose API setup and then use the HONC template to create our own serverless API.

Goose API: Explore the HONC components

Either get the Goose Quotes API via your CLI (as described above) or clone it’s repo. The repository’s README provides instructions on how to set up and run the project. Here are some additional details and explanations about the individual steps:

1. Setting up API keys and Database direction

To run the project, you need to provide your DATABASE_URL and an OPENAI_API_KEY in a .dev.vars file at the root of your project:

DATABASE_URL="your-db-address"
OPENAI_API_KEY="your-openeai-api-key"
Enter fullscreen mode Exit fullscreen mode

The drizzle.config.ts sets the path towards the .dev.vars file for creating the database tables at the defined destination. Later when running the code the Cloudflare worker needs access to the database to get and insert information to the database. Additionally the business logic requires a key for OpenAI to generate goose quotes and bios.

2. Install dependencies: yarn install

3. Generate Database: yarn db:generate

This script will generate the database table structure. The structure is defined in the db/schema.ts. The command creates a new folder called drizzle in your project, which includes the SQL statements and a detailed JSON schema

4. Migrate Database: yarn db:migrate

This command will migrate your table to your Neon database. After running this command successfully, you can verify within your Neon project that the table has been created.

5. Run the project locally: yarn dev

This starts up your cloud worker locally. You can visit your browser at localhost:8787. It is time to explore and test the application.

6. Interact with the local running API using FPX: npx @fiberplane/studio

To inspect the serverless API locally, you can use FPX, which functions like Postman for your internal APIs. FPX interacts with your API endpoints and provides insights into your code and request structures. The Goose Quotes API code uses the FPX Hono Middleware:

   import { createHonoMiddleware } from '@fiberplane/hono';
   ...
   const app = new Hono<{ Bindings: Bindings }>()
   app.use(createHonoMiddleware(app));  
Enter fullscreen mode Exit fullscreen mode

With FPX and Hono middleware, FPX gains access to your application endpoints. When running alongside your local application, FPX detects these endpoints and has visibility into the code logic and request body structure. FPX enables you to send requests, track call chains, and visualize stack traces for easier debugging.

FPX UI: detected endpoints of the goose quote API application

FPX UI: Trace information of a REST call

Additionally, FPX features an AI tool that helps create request bodies for the API. You can provide your OpenAI key in the FPX UI under settings to leverage this feature. FPX can also test your API with hostile scenarios, helping to identify potential data handling issues.

FPX UI: AI feature

7. Deploy to Cloudflare : yarn run deploy

After exploring your application locally with FPX and also very important writing tests, the final step is to deploy the Goose API to the cloud.

HONC Template: Create your own HONC project

The HONC template is part of the creat-honc-app cli and allows one to get started quickly with an own project. It sets up a project structure with Drizzle, Hono, and Cloudflare Workers. The CLI command: npm create honc-app@latest (select: bare template) initializes the template.

The ReadMe file guides you through the commands to generate and migrate the database tables, run the Cloudflare worker locally, and deploy to Cloudflare. It is important to specify the DATABASE_URL in the .dev.vars file at the root of the project.

The template provides an index.ts file with two pre-configured endpoints.

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

app.get('/api/users', async (c) => {
  const sql = neon(c.env.DATABASE_URL)
  const db = drizzle(sql);

  return c.json({
    users: await db.select().from(users)
  })
})
Enter fullscreen mode Exit fullscreen mode

It also defines a table to store users in the schema.ts file. Additionally, it provides a drizzle.config.ts file to read the DATABASE_URL from the .dev.vars file for creating the tables at the desired destination. Furthermore, it contains a seed.ts file to prefill the database with some users, so the /api/users endpoint has data to return.

When creating your own serverless API, the schema.ts file should represent your business logic's data schema. Once the schema is defined, the application endpoints can be configured and populated with their own business logic.

HONCing away

The Honc stack focuses on Hono as a web framework and combines it to a stack using database and cloud technology to get started quickly with new projects . By using the HONC stack, you can streamline the development process and concentrate on building your API without getting bogged down by setting up different tools. The structured template and interchangeable components facilitate efficient development and deployment. FPX aids in exploring and testing the API calls locally, providing valuable insights into call chains and traces, which can be more convenient than debugging solely in the terminal. So, let's keep our focus on the business logic and let the HONC stack handle the rest.

Top comments (0)