SampleAPIs

repository·main·Indexed 42 days ago

https://github.com/jermbo/sampleapis

A free, authentication-free playground of sample REST endpoints designed for learning and testing RESTful API interactions. Version 3.0.0 features an Express-based API server and a React client with an interactive CodeMirror-powered Playground, HTTP Inspector, and guided learning challenges. It supports standard REST conventions, CRUD operations, and advanced querying, filtering, sorting, and pagination.

Tokens
44.1K
Snippets
87
Records
212
Agent score
53%

What's inside SampleAPIs

  1. Overview of Client Features

    main

    The React client for Sample APIs is composed of several specialized modules designed for exploring and testing APIs. Key features include:

    • Navigation & Routing: File-based routing with layouts and view transitions.
    • Data Management: Server state is managed via TanStack Query, while UI state uses minimal React Context.
    • API Exploration: Dedicated API detail pages featuring endpoint switchers and a sandboxed Playground.
    • Interactive Playground: A CodeMirror-powered editor that runs code in a sandboxed iframe, including an HTTP Inspector to monitor network requests (status, timing, headers).
    • Data Visualization: An Explore Panel for viewing field shapes and building queries, and a JSON Tree Viewer for collapsible data inspection.
    • Learning System: Guided Challenges (/learn) which provide ordered exercises that execute in the Playground and are graded via an event stream and specific check specs.
    • Styling: A plain-CSS design system based on design tokens.
  2. Overview of Endpoint Data in Sample APIs

    main
    The Sample APIs service is built around JSON datasets that serve as the core product. These datasets are structured as JSON files that include metadata, collections, and unique identifiers. The lifecycle of an endpoint involves a specific file format, a process for making endpoints live via a registry rebuild, and a mechanism for data recovery using backup files.
  3. Understand the Sample APIs monorepo structure

    main

    The project is organized as a two-app monorepo consisting of a backend API server and a frontend React client. The root package.json manages the orchestration of both applications using concurrently via the npm run dev command.

    Backend (server/)

    • Runtime: Express 5 (CommonJS JavaScript).
    • Data Storage: Located in server/api/. Each API is stored as a <name>.json file accompanied by a .json.backup file.
    • Routing: Express routers are located in server/routes/ and handle data APIs, frontend lists, resets, creation, and testing.
    • Utilities: server/utils/ contains core logic for JSON routing, validation, rate limiting, and registry generation.
    • Legacy Assets: server/views/ and server/public/ contain a deprecated Pug-based site.

    Frontend (client/)

    • Runtime: Vite + React 19 + TypeScript.
    • Routing: Uses file-based routing via TanStack Router, with definitions in client/src/routes/ and rendered components in client/src/pages/.
    • Components: Shared UI elements (e.g., Header, APICard, Playground) are located in client/src/components/.
    • Styling: Uses a plain-CSS design system located in client/src/styles/.

    Other Directories

    • Documentation: The project wiki is located in docs/.
    • Testing: Manual endpoint testing can be performed using the Bruno/OpenCollection request collection found in endpoint-test/.
  4. Explore SampleAPIs documentation sections

    main

    The SampleAPIs documentation is organized into several functional areas:

    SectionCoverage
    ArchitectureThe two apps, the tech stack, and request flow
    API SurfaceREST conventions, queries, CRUD, rate limits, errors, and service routes
    Endpoint DataJSON datasets, format, registry, resets, and custom endpoints
    Client FeaturesRouting, state, the Playground, and styling
    OperationsLocal development, Docker, deployment, and testing
    ContributingSetup, code style, and pull request flow
    DecisionsArchitectural trade-offs and revisit triggers
    Future FeaturesProposed features and implementation plans
    GlossaryShared project vocabulary
  5. Server-side Tech Stack Overview

    main

    The server is built using the following technologies:

    • Express 5: Handles routing and middleware. Note that rejected async handlers flow to the central error handler natively.
    • helmet: Provides security headers (CSP is disabled for legacy Pug pages).
    • cors: Configured with permissive CORS to support its role as a public API.
    • express-rate-limit: Used for request throttling.
    • morgan: Handles request logging (dev mode for local development, combined for production).
    • pug: Used for templating legacy site pages and reset/create pages.
    • jest & nodemon: Dev-only tools for testing and file-watching restarts.

    Note: The server intentionally uses no database and no ORM; it relies on flat JSON files.

  6. Client-side Tech Stack Overview

    main

    The client application is built with the following technologies:

    • React 19 + TypeScript: Core UI framework.
    • Vite 8 (with SWC plugin): Build tool and development server.
    • TanStack Router: Provides file-based routing with automatic code-splitting.
    • TanStack Query: Manages server state and caching.
    • CodeMirror 6: Powers the Playground editor.
    • Fontsource: Provides self-hosted Roboto and Montserrat Alternates fonts.
    • oxlint: Used for linting (replaces ESLint).
  7. Explore the Sample APIs REST interface

    main

    The Sample APIs service exposes a RESTful interface via an Express server. The API follows specific conventions for resource access, querying, and data manipulation.

    Key areas of the API surface include:

    • REST Conventions: URL structures, resource types (collections vs. singular), and json-server compatibility.
    • Querying & Filtering: Using equality, dot paths, operator suffixes, and the full-text q parameter.
    • Sorting & Pagination: Controlling result order with _sort/_order and managing result sets with _page/_limit and Link headers.
    • CRUD & Validation: Write semantics, data shape validation, and per-file locking mechanisms.
    • Rate Limiting: Understanding global and per-API rate limits.
    • Error Responses: Standardized error shapes and their triggers.
    • Service Routes: Specialized endpoints like /health, /frontend, /resetit, /create, /generate, and /test.
  8. Core characteristics of the SampleAPIs service

    main

    When using or building on SampleAPIs, keep these operational traits in mind:

    • No Authentication: The service is designed for learning; anyone can perform read and write operations without credentials.
    • Rate Limiting: To prevent abuse, the service employs two request limiters.
    • Self-healing: The system is designed to be self-healing by periodically restoring data from the .json.backup files.
    • Legacy Routes: The server includes a legacy Pug-rendered site accessible at the / route.
  9. Review proposed future features for SampleAPIs

    main

    SampleAPIs is evolving from a data-fetching service into a learning tool. Several feature proposals are currently under consideration. These proposals are categorized by their learning impact, implementation effort, and current status.

    Proposed Features Overview:

    FeatureDescriptionLearning ImpactEffort
    HTTP InspectorA mini Network tab next to the Playground consoleHighSmall
    Query BuilderVisual UI for filter/sort/pagination syntaxHighSmall–Medium
    Guided ChallengesPer-API exercises with validated solutionsVery highLarge
    Response Shape ViewerDerived field/type view per endpoint, copy as TypeScriptMediumSmall–Medium
    Multi-Language Snippetscurl / Python / Node tabs for the current endpointMediumSmall
    TypeScript PlaygroundTS-default editor with live checking and endpoint typesHighMedium–Large
    Error Practice Routeshttpbin-style delay/status/flaky endpointsHighMedium
    Auth Training WheelsOpt-in demo API that teaches token authMedium–HighMedium–Large
    Scratch EndpointsUser-supplied temporary CRUD endpointsHighLarge

    Note: Shareable Playground Links has been rejected; playground state remains client-side in IndexedDB and is not URL-encoded.

  10. How the Query Builder architecture works

    main

    The Query Builder is a purely client-side implementation hosted within the APIDetails.tsx page. It follows this data flow:

    1. Field Discovery: The system fetches a sample of the active endpoint (using ?_limit=N) and uses a shared utility deriveShape() to identify available field paths and types.
    2. User Input: Users interact with a Field Picker, Filter rows, Sort controls, and Pagination controls.
    3. State Management: All inputs update a single state object containing filters, q, sort, and pagination.
    4. URL Generation: A pure function buildQueryString(state) converts the state into a valid URL string, which is displayed in a live URL bar.
    5. Preview: A debounced fetch (~400ms) is triggered by URL changes to preview results using the JsonTree component. The total record count is displayed using the X-Total-Count header.
  11. Data model for Multi-Language Snippets

    main

    To implement copy-only snippets (curl, Python, Node) alongside existing runnable JavaScript snippets, a new parallel export COPY_SNIPPETS is used. This prevents accidental mixing of runnable and copy-only code.

    Each entry in COPY_SNIPPETS represents a language and contains multiple variants (e.g., GET, GET with query, POST) that use a build(url) function to interpolate the active endpoint URL.

    Constraints for POST snippets:

    • Snippet bodies must satisfy the server's shape validation defined in server/utils/verifyData.js.
    • Bodies should be generic-but-valid or include a comment noting the expected shape to avoid errors.
    // Proposed structure for COPY_SNIPPETS
    COPY_SNIPPETS: { 
      id: string, 
      label: string, 
      language: string, 
      variants: { 
        id: string, 
        label: string, 
        build(url: string): string 
      }[] 
    }[]
  12. Understand the Docker service architecture

    main

    The stack consists of two primary services running within an app-network:

    1. server:

      • Runs the Node.js application (sampleapis.js) on port 5555.
      • Installs production dependencies only (npm ci --omit=dev).
      • Runs as an unprivileged node user.
      • While the image defaults to NODE_ENV=production, Docker Compose overrides this to development to enable dev logging via morgan.
      • Includes a healthcheck that performs a wget /health every 10 seconds.
    2. client:

      • Builds the application using tsc && vite build.
      • Serves the production bundle using vite preview on port 4444.
      • Dependency Note: The client service is configured to wait and start only after the server service reports a healthy status via its healthcheck.