openapi: 3.1.0
info:
  title: StormPull API
  version: 1.0.0
  description: |
    Historical hail data for any address or coordinate in the contiguous United States, built on NOAA's MRMS MESH
    radar hail estimates from October 2020 onward, for insurance, roofing, real estate, and weather analytics.

    ## Authentication

    The hail and account usage endpoints require an API key passed via the `X-API-Key` header.
    Keys are prefixed with `ht_live_` and issued during signup. Store your key securely — it
    cannot be retrieved after creation.

    ## Lookups

    Each successful (200) hail query counts as one lookup against your plan allowance. A request
    that returns an error is never counted. The sandbox plan includes 100 lookups in total and
    stops at that allowance with `402 PAYMENT_REQUIRED`; paid plans continue past their monthly
    allowance and bill the extra lookups as overage.

    ## Storm days

    Hail history comes from NOAA MRMS MESH (Maximum Estimated Size of Hail), a radar estimate built from the NEXRAD
    network on a grid of roughly 1 km cells (https://www.nssl.noaa.gov/projects/mrms/), and records begin in October 2020. A storm crosses many cells, so each hail event in a response is one storm day: a day
    with hail recorded within the search radius, with that day's largest hail, the distance to the nearest cell that
    recorded it, and the number of cells it covered (`cell_count`). `events_found`, the Storm Exposure Score and its
    summary counts all count storm days. Pass `granularity=cell` to get one event per radar cell instead.

    ## Rate Limits

    Each account may make a set number of requests per minute, by plan. Every authenticated request to the hail
    endpoints, and to `/v1/account/usage` when called with an API key, counts toward the current clock minute, including
    requests that end in an error. Requests over the limit get `429 RATE_LIMIT_EXCEEDED` with a `Retry-After` header and
    are never counted as lookups. Counted responses carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` and
    `X-RateLimit-Reset` (Unix time in seconds when the window resets).

    | Plan       | Requests/min |
    |------------|--------------|
    | Sandbox    | 10           |
    | Starter    | 60           |
    | Growth     | 120          |
    | Scale      | 300          |
    | Reports    | 60           |
    | Enterprise | 600          |

    ## Errors

    All errors follow a consistent JSON structure with a machine-readable `code`, a human-readable
    `message`, and a `docs` link to the code's entry on https://stormpull.com/docs.
  contact:
    name: StormPull Support
    email: danny@stormpull.com
    url: https://stormpull.com
  license:
    name: Proprietary
    url: https://stormpull.com/terms

servers:
  - url: https://stormpull.com/api
    description: Production

tags:
  - name: Health
    description: Public health and status endpoints
  - name: Auth
    description: Account creation
  - name: Hail
    description: Historical hail event queries
  - name: Account
    description: Account usage and analytics

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: API key starting with `ht_live_`

  parameters:
    RadiusMiles:
      name: radius_miles
      in: query
      required: false
      description: |
        Search radius in miles, 0.1 to 25. Larger values are capped at 25 and smaller positive values raised to 0.1;
        `search.radius_miles` in the response shows the radius used. 0, negative or non-numeric values return 400 INVALID_PARAMS.
      schema:
        type: number
        default: 1
        exclusiveMinimum: 0
    YearsBack:
      name: years_back
      in: query
      required: false
      description: |
        Years of history to search, a whole number from 1 to 10. Larger values are capped at 10; `search.years_back` in the
        response shows the value used. Records begin in October 2020, so a window reaching back further returns the same
        history. 0, negative, fractional or non-numeric values return 400 INVALID_PARAMS.
      schema:
        type: integer
        default: 5
        minimum: 1
    MinHailSize:
      name: min_hail_size
      in: query
      required: false
      description: Minimum hail diameter in inches, 0 or more. Negative values return 400 INVALID_PARAMS.
      schema:
        type: number
        default: 0.75
        minimum: 0
    Granularity:
      name: granularity
      in: query
      required: false
      description: |
        `day` returns one event per storm day. `cell` returns one event per ~1 km radar cell, which is how every response
        was shaped before storm days were introduced; `events_found` then counts cells and each `cell_count` is 1.
      schema:
        type: string
        enum: [day, cell]
        default: day
    IncludeScore:
      name: include_score
      in: query
      required: false
      description: |
        `true` (or `1`) appends the Storm Exposure Score. Scoring uses every storm day of any hail size within
        `radius_miles` in the last 10 years (records begin in October 2020), regardless of `years_back`, `min_hail_size`
        and `granularity`, and consumes no extra lookup.
      schema:
        type: boolean
        default: false

  headers:
    X-RateLimit-Limit:
      description: Requests per minute the account's plan allows
      schema:
        type: integer
        examples: [60]
    X-RateLimit-Remaining:
      description: Requests left in the current one-minute window
      schema:
        type: integer
        examples: [42]
    X-RateLimit-Reset:
      description: Unix time, in seconds, when the current window ends and the count resets
      schema:
        type: integer
        examples: [1764525660]
    Retry-After:
      description: Seconds to wait before the next request will be accepted
      schema:
        type: integer
        minimum: 1
        maximum: 60
        examples: [23]

  responses:
    BadRequest:
      description: |
        Invalid parameters (`INVALID_PARAMS`) or an address that cannot be used (`INVALID_ADDRESS`). Not counted as a lookup.
      headers:
        X-RateLimit-Limit:
          $ref: "#/components/headers/X-RateLimit-Limit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/X-RateLimit-Remaining"
        X-RateLimit-Reset:
          $ref: "#/components/headers/X-RateLimit-Reset"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    PaymentRequired:
      description: Sandbox lookup allowance used up. Not counted as a lookup.
      headers:
        X-RateLimit-Limit:
          $ref: "#/components/headers/X-RateLimit-Limit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/X-RateLimit-Remaining"
        X-RateLimit-Reset:
          $ref: "#/components/headers/X-RateLimit-Reset"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    TooManyRequests:
      description: |
        More requests in the current minute than the plan allows (`RATE_LIMIT_EXCEEDED`). Not counted as a lookup; retry
        after `Retry-After` seconds.
      headers:
        Retry-After:
          $ref: "#/components/headers/Retry-After"
        X-RateLimit-Limit:
          $ref: "#/components/headers/X-RateLimit-Limit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/X-RateLimit-Remaining"
        X-RateLimit-Reset:
          $ref: "#/components/headers/X-RateLimit-Reset"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              code: RATE_LIMIT_EXCEEDED
              message: Rate limit of 10 requests per minute exceeded. Retry after 23 seconds.
              docs: https://stormpull.com/docs#RATE_LIMIT_EXCEEDED
    InternalError:
      description: Internal error. Not counted as a lookup; retry with exponential backoff.
      headers:
        X-RateLimit-Limit:
          $ref: "#/components/headers/X-RateLimit-Limit"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/X-RateLimit-Remaining"
        X-RateLimit-Reset:
          $ref: "#/components/headers/X-RateLimit-Reset"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"

  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message, docs]
          properties:
            code:
              type: string
              enum: [INVALID_ADDRESS, INVALID_PARAMS, INVALID_API_KEY, PAYMENT_REQUIRED, RATE_LIMIT_EXCEEDED, INTERNAL_ERROR]
              examples: [INVALID_API_KEY]
            message:
              type: string
              examples: [API key is missing, revoked, or malformed.]
            docs:
              type: string
              format: uri
              examples: [https://stormpull.com/docs#INVALID_API_KEY]

    HailEvent:
      type: object
      description: One storm day, or with `granularity=cell` one radar cell
      required: [date, hail_size_inches, source, distance_miles, storm_report_available, cell_count]
      properties:
        date:
          type: string
          format: date
          examples: ["2024-06-15"]
        hail_size_inches:
          type: number
          description: Largest estimated hail size that day within the search radius
          examples: [1.25]
        source:
          type: string
          enum: [MESH]
        distance_miles:
          type: [number, "null"]
          description: Distance from the queried point to the nearest radar cell that recorded hail that day, rounded to 0.01 mile
          examples: [0.8]
        storm_report_available:
          type: boolean
          description: Reserved for matching NOAA Storm Events ground reports, which lookups don't use yet; currently always false
        cell_count:
          type: integer
          minimum: 1
          description: Radar cells within the search radius that recorded hail that day (1 with `granularity=cell`)
          examples: [9]

    HailResults:
      type: object
      required: [events, events_found, largest_hail_inches, last_event_date]
      properties:
        events:
          type: array
          description: One entry per storm day (or per radar cell with `granularity=cell`), most recent first
          items:
            $ref: "#/components/schemas/HailEvent"
        events_found:
          type: integer
          description: Number of entries in `events`
          examples: [12]
        largest_hail_inches:
          type: [number, "null"]
          examples: [2.5]
        last_event_date:
          type: [string, "null"]
          format: date
          examples: ["2024-06-15"]

    SearchParams:
      type: object
      description: The search that ran, after any capping of oversized values
      required: [radius_miles, years_back, min_hail_size, granularity]
      properties:
        radius_miles:
          type: number
          examples: [1]
        years_back:
          type: integer
          examples: [5]
        min_hail_size:
          type: number
          examples: [0.75]
        granularity:
          type: string
          enum: [day, cell]

    Usage:
      type: object
      required: [lookups_used, lookups_included, is_overage]
      properties:
        lookups_used:
          type: integer
          description: Lookups used in the current period, including this one
          examples: [43]
        lookups_included:
          type: integer
          examples: [100]
        is_overage:
          type: boolean

    StormScore:
      type: object
      description: Storm Exposure Score, present only when `include_score` is true
      required: [value, tier, tier_color, narrative, factors, summary]
      properties:
        value:
          type: integer
          minimum: 0
          maximum: 100
          examples: [74]
        tier:
          type: string
          enum: [Low, Moderate, High, Severe]
        tier_color:
          type: string
          description: Hex color for the tier
          examples: ["#ea580c"]
        narrative:
          type: string
          description: Plain-language summary of the property's hail exposure
        factors:
          type: object
          required: [recent_severity_pts, damaging_count_36mo_pts, peak_historical_pts, damaging_frequency_pts, recency_pts]
          properties:
            recent_severity_pts:
              type: integer
              maximum: 30
            damaging_count_36mo_pts:
              type: integer
              maximum: 20
            peak_historical_pts:
              type: integer
              maximum: 25
            damaging_frequency_pts:
              type: integer
              maximum: 15
            recency_pts:
              type: integer
              maximum: 10
        summary:
          type: object
          description: |
            Counts are storm days within `radius_miles`. The `_10yr` names are kept for compatibility: the window is the
            last 10 years, and records begin in October 2020. Damaging means a largest hail of 0.75 inches or more that day.
          required:
            - total_events_10yr
            - damaging_events_10yr
            - largest_hail_inches
            - largest_hail_date
            - events_last_12mo
            - events_last_36mo
            - most_recent_event_date
            - most_recent_hail_inches
            - largest_last_24mo_inches
            - largest_last_24mo_date
            - days_since_last_event
          properties:
            total_events_10yr:
              type: integer
            damaging_events_10yr:
              type: integer
            largest_hail_inches:
              type: number
            largest_hail_date:
              type: [string, "null"]
              format: date
            events_last_12mo:
              type: integer
            events_last_36mo:
              type: integer
            most_recent_event_date:
              type: [string, "null"]
              format: date
            most_recent_hail_inches:
              type: [number, "null"]
            largest_last_24mo_inches:
              type: number
            largest_last_24mo_date:
              type: [string, "null"]
              format: date
            days_since_last_event:
              type: [integer, "null"]

    ApiCall:
      type: object
      properties:
        id:
          type: string
          description: Numeric call ID, serialized as a string
          examples: ["9812"]
        timestamp:
          type: string
          format: date-time
        endpoint:
          type: string
          examples: [/v1/hail/address]
        address_queried:
          type: [string, "null"]
        response_ms:
          type: integer
        http_status:
          type: integer
        events_returned:
          type: integer
          description: Storm days returned (radar cells for calls made with `granularity=cell`)
        is_overage:
          type: boolean

    ServiceHealth:
      type: object
      required: [name, status, latency_ms]
      properties:
        name:
          type: string
        status:
          type: string
          enum: [operational, degraded, down]
        latency_ms:
          type: integer

paths:
  /health:
    get:
      operationId: getHealth
      summary: Health check
      description: Simple liveness probe that verifies database connectivity.
      tags: [Health]
      security: []
      responses:
        "200":
          description: Service is healthy
          content:
            application/json:
              schema:
                type: object
                required: [status, service, version, db]
                properties:
                  status:
                    type: string
                    const: ok
                  service:
                    type: string
                    const: stormpull-api
                  version:
                    type: string
                    examples: ["1.0.0"]
                  db:
                    type: string
                    enum: [ok, error]

  /status:
    get:
      operationId: getStatus
      summary: Service status
      description: |
        Comprehensive health check covering the API server, database, and NOAA data pipeline.
        The pipeline status is determined by the most recent GitHub Actions workflow run.
      tags: [Health]
      security: []
      responses:
        "200":
          description: Status report
          content:
            application/json:
              schema:
                type: object
                required: [status, checked_at, services]
                properties:
                  status:
                    type: string
                    enum: [operational, degraded, down]
                  checked_at:
                    type: string
                    format: date-time
                  services:
                    type: array
                    items:
                      $ref: "#/components/schemas/ServiceHealth"

  /v1/auth/signup:
    post:
      operationId: signup
      summary: Create an account
      description: |
        Creates a new sandbox account and returns a one-time API key.
        **Save the key immediately — it cannot be retrieved later.**
      tags: [Auth]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email:
                  type: string
                  format: email
                  examples: [user@example.com]
      responses:
        "201":
          description: Account created
          content:
            application/json:
              schema:
                type: object
                required: [message, api_key, plan, lookups_included, warning]
                properties:
                  message:
                    type: string
                  api_key:
                    type: string
                    description: One-time display of the full API key
                    examples: [ht_live_abc123def456...]
                  plan:
                    type: string
                    const: sandbox
                  lookups_included:
                    type: integer
                    const: 100
                  warning:
                    type: string
        "400":
          description: Invalid or duplicate email
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /v1/hail/address:
    get:
      operationId: getHailByAddress
      summary: Query hail events by address
      description: |
        Geocodes the given address and returns the storm days with hail recorded within the
        specified radius, most recent first. Each successful call counts as one lookup against your
        plan allowance; errors are not counted.

        The address must resolve within the contiguous US to a street address, building, or ZIP code.
        A city, state, or non-US address returns `400 INVALID_ADDRESS`.
      tags: [Hail]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: address
          in: query
          required: true
          description: US street address, building, or ZIP code to geocode
          schema:
            type: string
          examples:
            street:
              value: 1600 Pennsylvania Ave NW, Washington, DC 20500
            zip:
              value: "75201"
        - $ref: "#/components/parameters/RadiusMiles"
        - $ref: "#/components/parameters/YearsBack"
        - $ref: "#/components/parameters/MinHailSize"
        - $ref: "#/components/parameters/Granularity"
        - $ref: "#/components/parameters/IncludeScore"
      responses:
        "200":
          description: Hail history found
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
          content:
            application/json:
              schema:
                type: object
                required: [address, search, results, usage]
                properties:
                  address:
                    type: object
                    required: [input, formatted, lat, lon, confidence]
                    properties:
                      input:
                        type: string
                      formatted:
                        type: string
                        description: The geocoder's formatted address
                      lat:
                        type: number
                      lon:
                        type: number
                      confidence:
                        type: string
                        enum: [ROOFTOP, RANGE_INTERPOLATED, GEOMETRIC_CENTER, APPROXIMATE]
                  search:
                    $ref: "#/components/schemas/SearchParams"
                  results:
                    $ref: "#/components/schemas/HailResults"
                  score:
                    $ref: "#/components/schemas/StormScore"
                  usage:
                    $ref: "#/components/schemas/Usage"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/PaymentRequired"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"

  /v1/hail/coordinate:
    get:
      operationId: getHailByCoordinate
      summary: Query hail events by coordinates
      description: |
        Returns the storm days with hail recorded near the given latitude/longitude within the
        contiguous US (CONUS), most recent first. Each successful call counts as one lookup against
        your plan allowance; errors are not counted.
      tags: [Hail]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: lat
          in: query
          required: true
          description: Latitude (CONUS bounds 24–50)
          schema:
            type: number
            minimum: 24
            maximum: 50
          examples:
            denver:
              value: 39.7392
        - name: lon
          in: query
          required: true
          description: Longitude (CONUS bounds −125 to −66)
          schema:
            type: number
            minimum: -125
            maximum: -66
          examples:
            denver:
              value: -104.9903
        - $ref: "#/components/parameters/RadiusMiles"
        - $ref: "#/components/parameters/YearsBack"
        - $ref: "#/components/parameters/MinHailSize"
        - $ref: "#/components/parameters/Granularity"
        - $ref: "#/components/parameters/IncludeScore"
      responses:
        "200":
          description: Hail history found
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
          content:
            application/json:
              schema:
                type: object
                required: [coordinates, search, results, usage]
                properties:
                  coordinates:
                    type: object
                    required: [lat, lon]
                    properties:
                      lat:
                        type: number
                      lon:
                        type: number
                  search:
                    $ref: "#/components/schemas/SearchParams"
                  results:
                    $ref: "#/components/schemas/HailResults"
                  score:
                    $ref: "#/components/schemas/StormScore"
                  usage:
                    $ref: "#/components/schemas/Usage"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          $ref: "#/components/responses/PaymentRequired"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"

  /v1/account/usage:
    get:
      operationId: getAccountUsage
      summary: Account usage stats
      description: |
        Returns plan details, lookup counters, and the 20 most recent API calls. Does not count as a lookup. Calls made with
        an API key count toward the rate limit.
      tags: [Account]
      security:
        - ApiKeyAuth: []
      responses:
        "200":
          description: Usage stats
          headers:
            X-RateLimit-Limit:
              $ref: "#/components/headers/X-RateLimit-Limit"
            X-RateLimit-Remaining:
              $ref: "#/components/headers/X-RateLimit-Remaining"
            X-RateLimit-Reset:
              $ref: "#/components/headers/X-RateLimit-Reset"
          content:
            application/json:
              schema:
                type: object
                required: [plan, lookups_used, lookups_included, overage, total_api_calls, calls_last_24h, recent_calls]
                properties:
                  plan:
                    type: string
                    enum: [sandbox, starter, growth, scale, reports, enterprise]
                  lookups_used:
                    type: integer
                  lookups_included:
                    type: integer
                  overage:
                    type: boolean
                  total_api_calls:
                    type: integer
                  calls_last_24h:
                    type: integer
                  recent_calls:
                    type: array
                    items:
                      $ref: "#/components/schemas/ApiCall"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
