> ## Documentation Index
> Fetch the complete documentation index at: https://data.kushiro.app/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Aggregate numeric data

> Returns DB-side facet aggregation over `fact_metric` (e.g. "top 10 towns by latest population") so clients avoid fetching every row to aggregate locally. `source` and `group_by` are required. Buckets are ordered by `aggregated_value` and capped at `limit`; `truncated` flags when more buckets exist.



## OpenAPI

````yaml /openapi.json get /api/v1/metrics/aggregate
openapi: 3.1.0
info:
  title: k-Data
  version: 0.1.0
  description: >-
    Preview read-only API for reshaped public data collected from Kushiro City
    sources. Response shapes, URLs, and published datasets may change without
    notice.
  license:
    name: CC BY 4.0
    url: https://creativecommons.org/licenses/by/4.0/deed.ja
servers:
  - url: https://data.kushiro.app
    description: Production
security: []
tags:
  - name: service
    description: Service metadata and health endpoints.
  - name: sources
    description: Published source summaries.
  - name: metrics
    description: Numeric data records.
  - name: points
    description: >-
      Facility and location-style data records such as public facilities, AED
      locations, evacuation sites, and indexes.
  - name: terms
    description: Terms of use and attribution notes.
paths:
  /api/v1/metrics/aggregate:
    get:
      tags:
        - metrics
      summary: Aggregate numeric data
      description: >-
        Returns DB-side facet aggregation over `fact_metric` (e.g. "top 10 towns
        by latest population") so clients avoid fetching every row to aggregate
        locally. `source` and `group_by` are required. Buckets are ordered by
        `aggregated_value` and capped at `limit`; `truncated` flags when more
        buckets exist.
      operationId: aggregateMetrics
      parameters:
        - $ref: '#/components/parameters/SourceQuery'
        - name: group_by
          in: query
          required: true
          description: Aggregation axis.
          schema:
            type: string
            enum:
              - town
              - age_bucket
              - category
              - metric
              - period
        - name: agg
          in: query
          required: false
          description: >-
            Aggregation function. `latest` returns the value of the most recent
            period within each bucket; `delta` returns (latest - previous) and
            adds `previous_value` / `previous_period` / `delta_pct` to each
            bucket.
          schema:
            type: string
            enum:
              - sum
              - avg
              - min
              - max
              - latest
              - delta
            default: latest
        - name: order
          in: query
          required: false
          description: Sort direction for `aggregated_value`. `desc` returns the top N.
          schema:
            type: string
            enum:
              - asc
              - desc
            default: desc
        - name: metric
          in: query
          required: false
          description: >-
            Pre-filter by metric name (exact). Repeat the parameter to match any
            of several metrics. Takes precedence over `metric_prefix`.
          style: form
          explode: true
          schema:
            type: array
            items:
              type: string
              minLength: 1
            maxItems: 20
        - name: metric_prefix
          in: query
          required: false
          description: >-
            Pre-filter by metric name prefix. Ignored when `metric` is also
            supplied.
          schema:
            type: string
            minLength: 1
        - name: from
          in: query
          required: false
          description: >-
            Inclusive lower bound for `period.start_date` in `YYYY-MM-DD`
            format.
          schema:
            $ref: '#/components/schemas/DateString'
        - name: to
          in: query
          required: false
          description: Inclusive upper bound for `period.end_date` in `YYYY-MM-DD` format.
          schema:
            $ref: '#/components/schemas/DateString'
        - name: town
          in: query
          required: false
          description: Pre-filter by exact town name.
          schema:
            type: string
            minLength: 1
        - name: age
          in: query
          required: false
          description: Pre-filter by exact age label.
          schema:
            type: string
            minLength: 1
        - name: category_kind
          in: query
          required: false
          description: Pre-filter by `dim_category.kind`.
          schema:
            type: string
            minLength: 1
        - name: category_code
          in: query
          required: false
          description: Pre-filter by `dim_category.code`.
          schema:
            type: string
            minLength: 1
        - name: limit
          in: query
          required: false
          description: Maximum number of buckets to return. Defaults to 100.
          schema:
            type: integer
            minimum: 1
            maximum: 1000
            default: 100
      responses:
        '200':
          description: Metric aggregation result.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MetricsAggregateResult'
              examples:
                default:
                  value:
                    source: kushiro_population_by_town
                    group_by: town
                    agg: latest
                    buckets:
                      - value: 中央町
                        aggregated_value: 1234
                        count: 264
                        unit: persons
                        metric: population_total
                        period:
                          granularity: month
                          start_date: '2026-04-01'
                          end_date: '2026-04-30'
                          label: 2026-04
                    total: 67000
                    truncated: false
        '400':
          $ref: '#/components/responses/InvalidQueryParameters'
        '500':
          $ref: '#/components/responses/InternalServerError'
components:
  parameters:
    SourceQuery:
      name: source
      in: query
      required: true
      description: Source ID to query.
      schema:
        type: string
        minLength: 1
  schemas:
    DateString:
      type: string
      pattern: ^\d{4}-\d{2}-\d{2}$
      example: '2026-04-01'
    MetricsAggregateResult:
      type: object
      required:
        - source
        - group_by
        - agg
        - buckets
        - total
        - truncated
      properties:
        source:
          type: string
        group_by:
          type: string
        agg:
          type: string
        buckets:
          type: array
          items:
            $ref: '#/components/schemas/MetricFacetBucket'
        total:
          type: integer
          minimum: 0
          description: Total matching rows after filtering, before aggregation.
        truncated:
          type: boolean
          description: True when bucket cardinality exceeded `limit`.
      additionalProperties: false
    MetricFacetBucket:
      type: object
      required:
        - value
        - aggregated_value
        - count
        - unit
      properties:
        value:
          type:
            - string
            - 'null'
          description: >-
            Bucket value for the grouping axis. Null for whole-source rows
            lacking the dimension.
        aggregated_value:
          type: number
        count:
          type: integer
          minimum: 0
          description: Number of rows in the bucket before aggregation.
        unit:
          type:
            - string
            - 'null'
          description: Common unit across the bucket, or null when units are mixed.
        metric:
          type: string
          description: >-
            Present for agg=latest and agg=delta: the metric name of the most
            recent row in the bucket.
        period:
          $ref: '#/components/schemas/Period'
          description: >-
            Present for agg=latest and agg=delta: the most recent period in the
            bucket.
        previous_value:
          type: number
          description: >-
            Present for agg=delta: value of the previous period within the
            bucket.
        previous_period:
          $ref: '#/components/schemas/Period'
          description: 'Present for agg=delta: the previous period.'
        delta_pct:
          type:
            - number
            - 'null'
          description: >-
            Present for agg=delta: percentage change, or null when the previous
            value is 0.
      additionalProperties: false
    InvalidQueryError:
      type: object
      required:
        - error
        - issues
      properties:
        error:
          type: string
          example: invalid query parameters
        issues:
          type: array
          items:
            type: object
            required:
              - path
              - message
            properties:
              path:
                type: string
              message:
                type: string
            additionalProperties: false
      additionalProperties: false
    InternalServerError:
      type: object
      required:
        - error
      properties:
        error:
          type: string
          example: internal server error
      additionalProperties: false
    Period:
      type: object
      required:
        - granularity
        - start_date
        - end_date
        - label
      properties:
        granularity:
          type: string
          description: >-
            Time granularity label such as `month`, `year`, `calendar_year`, or
            `fiscal_year_h1`.
        start_date:
          $ref: '#/components/schemas/DateString'
        end_date:
          $ref: '#/components/schemas/DateString'
        label:
          type: string
      additionalProperties: false
  responses:
    InvalidQueryParameters:
      description: The query string failed validation.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/InvalidQueryError'
          examples:
            missingSource:
              value:
                error: invalid query parameters
                issues:
                  - path: source
                    message: 'Invalid input: expected string, received undefined'
    InternalServerError:
      description: Unexpected server error.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/InternalServerError'
          examples:
            default:
              value:
                error: internal server error

````