---
id: rating-api
name: Rating API
version: 1.0.0
summary: |
  Internal HTTP and A2A gRPC service for collecting, listing, deleting, and
  summarizing customer feedback for Catalog books.
readsFrom:
  - id: rating-database
    version: 1.0.0
  - id: rating-cache
    version: 1.0.0
writesTo:
  - id: rating-database
    version: 1.0.0
  - id: rating-cache
    version: 1.0.0
entities:
  - id: feedback
    version: 1.0.0
owners:
  - catalog-experience-team
badges:
  - content: Internal
    backgroundColor: gray
    textColor: gray
  - content: HTTP API
    backgroundColor: teal
    textColor: teal
diagrams:
  - id: rating-summarizer-workflow
    version: 1.0.0
receives:
  - id: CreateFeedback
    version: 1.0.0
    group: Feedback Commands
  - id: DeleteFeedback
    version: 1.0.0
    group: Feedback Commands
  - id: ListFeedbacks
    version: 1.0.0
    group: Feedback Queries
  - id: SummarizeFeedback
    version: 1.0.0
    group: Feedback Queries
  - id: BookUpdatedRatingFailedIntegrationEvent
    version: 1.0.0
    from:
      - id: "bookworm.{env}.catalog.book-update-rating-failed"
        parameters:
          env: development
sends:
  - id: FeedbackCreatedIntegrationEvent
    version: 1.0.0
    group: Feedback Events
    to:
      - id: "bookworm.{env}.rating.feedback-create"
        parameters:
          env: development
  - id: FeedbackDeletedIntegrationEvent
    version: 1.0.0
    group: Feedback Events
    to:
      - id: "bookworm.{env}.rating.feedback-delete"
        parameters:
          env: development
styles:
  icon: /icons/languages/dotnet.svg
specifications:
  - type: openapi
    path: openapi-v1.yaml
    name: OpenAPI V1
  - type: asyncapi
    path: asyncapi-v1.yml
    name: AsyncAPI V1
attachments:
  - url: https://foxminchan.github.io/BookWorm/docs/domains/reviews/1.0.0/engineering/feedback-contracts-and-integration
    title: Feedback contracts and integration
    description: HTTP routes, validation rules, Cosmos DB mapping, and Kafka contracts.
    type: documentation
  - url: https://foxminchan.github.io/BookWorm/docs/domains/reviews/1.0.0/guides/feedback-lifecycle
    title: Feedback lifecycle
    description: End-to-end lifecycle of customer feedback and its derived rating projection.
    type: guides
  - url: https://foxminchan.github.io/BookWorm/docs/domains/reviews/1.0.0/runbooks/catalog-rating-projection-failure
    title: Recover a failed Catalog rating projection
    description: Operational triage for BookUpdatedRatingFailedIntegrationEvent.
    type: runbooks
repository:
  language: C#
  url: "https://github.com/foxminchan/BookWorm"
---

## Service Responsibility & Boundary

Rating API is the system of record within the [[domain|reviews]] domain for individual customer [[entity|feedback]] records on Catalog books. It exposes versioned HTTP endpoints for feedback management and read-time AI summarization, hosts BookWorm's Agent-to-Agent (A2A) gRPC server for [[agent|rating-agent]], and synchronizes rating deltas with [[service|catalog-api]] over Kafka. Book metadata and derived rating totals remain owned by [[service|catalog-api]].

## Service Profile

| Property                                  | Value                                                                                                                                                                                  |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context / Domain**              | [[domain\|reviews]]                                                                                                                                                                    |
| **Owner Team**                            | [[team\|catalog-experience-team]]                                                                                                                                                      |
| **Runtime Style**                         | REST API, A2A gRPC Server, and Async Kafka Producer/Consumer                                                                                                                           |
| **Public / Gateway Exposure**             | Yes via API Gateway (HTTP) and Internal Only (A2A gRPC)                                                                                                                                |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT and Entra Agent Identity via [[system\|identity-provider]]; `admin` policy for deletion, `rating_read` scope for A2A gRPC                                       |
| **Owned Data Store(s)**                   | [[container\|rating-database]] (Azure Cosmos DB partitioned by book ID), [[container\|rating-cache]] (Redis read cache & idempotency)                                                  |
| **Key Resilience / Idempotency Pattern**  | Compensating delete on Catalog rejection, fail-closed PII screening, per-user rate limiting, and dead-letter routing on [[channel\|bookworm.&#123;env&#125;.rating.dead-letter-queue]] |

## Contracts & Data Ownership

Rating API owns the [[entity|feedback]] aggregate in [[container|rating-database]] and enforces uniqueness per `(bookId, firstName, lastName)`.

:::note
Read-time summarization via [[agent|rating-agent]] retrieves book metadata and analysis prompts from [[service|mcp-server]], reads raw reviews in-process under a rate cap, and screens inputs and outputs fail-closed through [[service|presidio-api]] without mutating stored feedback.
:::

:::warning
If [[service|catalog-api]] emits [[event|BookUpdatedRatingFailedIntegrationEvent]] because a reviewed book does not exist, Rating API executes an idempotent compensating delete on the orphaned feedback record.
:::

<MessageTable format="all" limit={10} showChannels={true} />

## Architecture Visualizations & Specifications

### Rating API Context

<MermaidFileLoader file="mermaids/RatingAPI-diagram-1.mmd" />

### Service Interactions

<NodeGraph />

### Owned Entities

<EntityMap />

## Attached Resources & Related Docs

<Attachments />

- [[doc|platform/006-api-and-contracts]] — Consolidated service, HTTP, gRPC, and Kafka directory.
- [[agent|rating-agent]] — AI review summarization agent contract.
- [[container|rating-database]] — Azure Cosmos DB persistence reference.
- [[container|rating-cache]] — Redis caching and idempotency reference.
- [[diagram|rating-summarizer-workflow]] — Read-time feedback summarization flow.


 ## Raw Schema:openapi-v1.yaml

openapi: 3.2.0
info:
  title: Rating Service API
  description: "Handles the collection, storage, and aggregation of user feedback and ratings for books on the BookWorm platform"
  contact:
    name: BookWorm Engineering
    url: https://github.com/foxminchan
    email: engineering@bookworm.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT
  version: "1.0"
  summary: A service responsible for managing user feedback and ratings for books on the BookWorm platform
paths:
  "/api/v1/feedbacks/{id}/summarize":
    get:
      tags:
        - Feedback
      summary: Summarize Feedback
      description: Summarize the feedback for a book by its ID
      operationId: SummarizeFeedbackEndpoint
      parameters:
        - name: id
          in: path
          description: The unique identifier of the book to be summarized
          required: true
          schema:
            type: string
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SummarizeResult"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
  /api/v1/feedbacks:
    get:
      tags:
        - Feedback
      summary: List Feedbacks
      description: List feedbacks for a book with pagination and filtering
      operationId: ListFeedbacksEndpoint
      parameters:
        - name: BookId
          in: query
          description: The ID of the book to get feedback for
          required: true
          schema:
            type: string
            format: uuid
        - name: PageIndex
          in: query
          description: Number of items to return in a single page of results
          schema:
            pattern: "^-?(?:0|[1-9]\\d*)$"
            type:
              - integer
              - string
            format: int32
            default: 1
        - name: PageSize
          in: query
          description: Number of items to return in a single page of results
          schema:
            pattern: "^-?(?:0|[1-9]\\d*)$"
            type:
              - integer
              - string
            format: int32
            default: 20
        - name: OrderBy
          in: query
          description: Property to order results by
          schema:
            type: string
            default: Rating
        - name: IsDescending
          in: query
          description: Whether to order results in descending order
          schema:
            type: boolean
            default: false
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/FeedbackDto"
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
    post:
      tags:
        - Feedback
      summary: Create Feedback
      description: Create a new feedback
      operationId: CreateFeedbackEndpoint
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateFeedbackCommand"
        required: true
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/FeedbackId"
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
  "/api/v1/feedbacks/{id}":
    delete:
      tags:
        - Feedback
      summary: Delete Feedback
      description: Delete a feedback if it exists
      operationId: DeleteFeedbackEndpoint
      parameters:
        - name: id
          in: path
          description: The unique identifier of the feedback to be deleted
          required: true
          schema:
            type: string
      responses:
        "204":
          description: No Content
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
components:
  schemas:
    CreateFeedbackCommand:
      required:
        - bookId
        - firstName
        - lastName
        - comment
        - rating
      type: object
      properties:
        bookId:
          type: string
          format: uuid
        firstName:
          type:
            - "null"
            - string
        lastName:
          type:
            - "null"
            - string
        comment:
          type:
            - "null"
            - string
        rating:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int32
    FeedbackDto:
      required:
        - id
        - firstName
        - lastName
        - comment
        - rating
        - bookId
      type: object
      properties:
        id:
          type: string
          format: uuid
        firstName:
          type:
            - "null"
            - string
        lastName:
          type:
            - "null"
            - string
        comment:
          type:
            - "null"
            - string
        rating:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int32
        bookId:
          type: string
          format: uuid
    FeedbackId:
      type: string
      format: uuid
    HttpValidationProblemDetails:
      type: object
      properties:
        type:
          type:
            - "null"
            - string
        title:
          type:
            - "null"
            - string
        status:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - "null"
            - integer
            - string
          format: int32
        detail:
          type:
            - "null"
            - string
        instance:
          type:
            - "null"
            - string
        errors:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
    ProblemDetails:
      type: object
      properties:
        type:
          type:
            - "null"
            - string
        title:
          type:
            - "null"
            - string
        status:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - "null"
            - integer
            - string
          format: int32
        detail:
          type:
            - "null"
            - string
        instance:
          type:
            - "null"
            - string
    RatingClassification:
      enum:
        - NoData
        - Bad
        - Good
        - TopRated
      default: NoData
    SummarizeResult:
      required:
        - summary
      type: object
      properties:
        summary:
          type: string
        classification:
          $ref: "#/components/schemas/RatingClassification"
        averageRating:
          pattern: "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$"
          type:
            - "null"
            - number
            - string
          format: double
        reviewCount:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int32
          default: 0
        evidence:
          type: string
          default: ""
        confidence:
          type: string
          default: ""
tags:
  - name: Feedback


 ## Raw Schema:asyncapi-v1.yml

---
asyncapi: 3.1.0
info:
  title: Rating API integration events
  version: 1.0.0
  description: |
    AsyncAPI contract for the Rating service's Kafka integration events.
    Rating publishes feedback lifecycle events for Catalog and consumes
    compensation events when Catalog cannot apply a rating update.
defaultContentType: application/cloudevents+json
channels:
  feedbackCreated:
    address: bookworm.{env}.rating.feedback-create
    description: Rating service publishes this event when feedback is created.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      feedbackCreated:
        $ref: "#/components/messages/FeedbackCreatedIntegrationEvent"
  feedbackDeleted:
    address: bookworm.{env}.rating.feedback-delete
    description: Rating service publishes this event when feedback is deleted.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      feedbackDeleted:
        $ref: "#/components/messages/FeedbackDeletedIntegrationEvent"
  bookUpdatedRatingFailed:
    address: bookworm.{env}.catalog.book-update-rating-failed
    description: Catalog publishes this event when a feedback-created event cannot update a book.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      bookUpdatedRatingFailed:
        $ref: "#/components/messages/BookUpdatedRatingFailedIntegrationEvent"
operations:
  sendFeedbackCreated:
    action: send
    channel:
      $ref: "#/channels/feedbackCreated"
    summary: Publish feedback-created events
    messages:
      - $ref: "#/channels/feedbackCreated/messages/feedbackCreated"
  sendFeedbackDeleted:
    action: send
    channel:
      $ref: "#/channels/feedbackDeleted"
    summary: Publish feedback-deleted events
    messages:
      - $ref: "#/channels/feedbackDeleted/messages/feedbackDeleted"
  receiveBookUpdatedRatingFailed:
    action: receive
    channel:
      $ref: "#/channels/bookUpdatedRatingFailed"
    summary: Consume failed rating update notifications
    messages:
      - $ref: "#/channels/bookUpdatedRatingFailed/messages/bookUpdatedRatingFailed"
components:
  parameters:
    env:
      description: BookWorm deployment environment.
      enum:
        - development
        - staging
        - production
      default: development
  messages:
    FeedbackCreatedIntegrationEvent:
      name: FeedbackCreatedIntegrationEvent
      title: Feedback created
      summary: A new rating was created for a book.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/FeedbackCreatedPayload"
    FeedbackDeletedIntegrationEvent:
      name: FeedbackDeletedIntegrationEvent
      title: Feedback deleted
      summary: An existing rating was deleted from a book.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/FeedbackDeletedPayload"
    BookUpdatedRatingFailedIntegrationEvent:
      name: BookUpdatedRatingFailedIntegrationEvent
      title: Book rating update failed
      summary: Catalog could not update a book rating for the feedback event.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/BookUpdatedRatingFailedPayload"
  schemas:
    FeedbackCreatedPayload:
      type: object
      additionalProperties: false
      required:
        - bookId
        - rating
        - feedbackId
      properties:
        bookId:
          type: string
          format: uuid
          description: Identifier of the book whose rating summary changes.
        rating:
          type: integer
          minimum: 0
          maximum: 5
          description: Rating value added to the book.
        feedbackId:
          type: string
          format: uuid
          description: Identifier of the feedback record.
    FeedbackDeletedPayload:
      type: object
      additionalProperties: false
      required:
        - bookId
        - rating
        - feedbackId
      properties:
        bookId:
          type: string
          format: uuid
          description: Identifier of the book whose rating summary changes.
        rating:
          type: integer
          minimum: 0
          maximum: 5
          description: Rating value removed from the book.
        feedbackId:
          type: string
          format: uuid
          description: Identifier of the deleted feedback record.
    BookUpdatedRatingFailedPayload:
      type: object
      additionalProperties: false
      required:
        - feedbackId
      properties:
        feedbackId:
          type: string
          format: uuid
          description: Identifier of the feedback that could not be applied.
