Back to blog
Guide

How to Build Type-Safe APIs in Dify with orpc-contract-first

Skill Gallery TeamJanuary 31, 20264 min read

API specification mismatches between frontend and backend cause runtime errors. A contract-first approach enables type-safe API development starting from type definitions.

This article explains how to build a type-safe API layer using oRPC patterns with the orpc-contract-first skill from the Dify repository.

What This Skill Does

orpc-contract-first guides type-safe API implementation using the contract-first pattern in Dify frontend:

  • oRPC contract definition (path, method, input, output)
  • Router registration with API prefix grouping
  • TanStack Query integration for custom hook generation
  • Automatic type inference (InferContractRouterInputs, etc.)

Designed for Dify frontend developers ensuring API type safety.

Installation

Prerequisites

  • Claude Code installed
  • Access to Dify project source code

Install Command

claude mcp add github.com/langgenius/dify/tree/main/.claude/skills/orpc-contract-first

Usage

Defining Contracts

Create contracts in web/contract/console/{domain}.ts:

import { oc } from '@orpc/contract'

export const systemContract = {
  getInfo: oc.route({ path: '/info', method: 'GET' }),
  updateSettings: oc.route({
    path: '/settings',
    method: 'POST',
    body: settingsSchema,
  }),
}

Router Registration

Nest by API prefix in web/contract/router.ts.

Custom Hook Creation

Create TanStack Query hooks in web/service/use-{domain}.ts. Query keys are auto-generated via consoleQuery.{group}.{contract}.queryKey().

Input Structure Rules

Inputs always use { params, query?, body? } format. Path parameters use {paramName} syntax.

Important Considerations

No Barrel Files

Per Dify conventions, avoid barrel files (re-exports from index.ts). Import directly from specific files.

oRPC and TypeScript Knowledge Required

This skill assumes familiarity with oRPC and TypeScript type systems. Consult oRPC documentation if new to the library.

Dify-Specific Patterns

Router nesting and query key naming conventions are specific to the Dify project and may not directly apply elsewhere.

Summary

orpc-contract-first enables type-safe API development in Dify frontend through the contract definition → router registration → hook generation workflow. Starting from type definitions prevents frontend-backend mismatches.

orpc-contract-first Skill Details

orpc-contract-firstdifytypescriptapitanstack-query

Related posts