Skip to content
API Now! is currently in closed beta. We are constantly updating these guides as we release updates!

PeerRelation (Semantic Module)

← Back to Modules Reference

In modern business applications, entities frequently connect as peers rather than as parent and child. Neither record owns the other, and both exist independently in your system:

  • A dish is paired with a beverage (Menu ↔\leftrightarrow Menu, e.g., Carne Asada Taco paired with Horchata).
  • A product suggests an accessory (Product →\rightarrow Product, e.g., Smartphone recommending a Protective Case).
  • An advanced course requires foundational coursework (Course →\rightarrow Course, e.g., CS201 requiring CS101).
  • A specialist is assigned to a client (Doctor →\rightarrow Patient).
  • An article cross-references related background research (Article →\rightarrow Article).

PeerRelation is the generalized default Many-to-Many (M:N) semantic module in API Now. It allows you to connect any two independent entities—including self-referencing relationships—while attaching rich business meaning, automated rules (such as cycle prevention), and custom relationship attributes.


AttributeSpecification
ScopeAssociation (Applied to a relationship between entities)
Relationship TypeMany-to-Many (multiple: true)
Has ConfigurationYes (nature, optional symmetry, optional customNature)
Default Settingsnature: 'recommendation', symmetry: 'directed'

In traditional database design, developers often create generic, untyped “join tables”. These raw link tables strip away business meaning—the system cannot tell whether a link represents a complementary recommendation, an operational assignment, or a strict prerequisite.

API Now avoids untyped join tables. While specialized semantic modules handle domain-specific workflows (like OrganizationMembers for tenant memberships or Tags for taxonomies), PeerRelation provides the standard, extensible foundation for all other peer-to-peer relationships.

  1. Clear Business Intent: Tagging relationships with a specific nature allows your API, UI, and connected AI agents to understand how items relate.
  2. Built-in Guardrails: For dependency workflows (prerequisites), the runtime automatically detects and prevents circular loops.
  3. First-Class Relationship Attributes: Store context directly on the connection (such as pairing scores, notes, or assignment dates) without creating intermediate junction entities.
  4. Collision-Proof Self-Referencing: Link entities of the same type (like dishes to dishes) with zero database naming conflicts—the platform handles link table naming and heuristics automatically under the hood.

When applying PeerRelation in the Data Modeler, you can configure the following settings:

The nature property defines the business purpose of the connection:

NatureReal-World Use CaseRuntime & Agent Behavior
recommendation (Default)Complementary Pairing
• Food & drink pairings (best_served_with)
• Outfit paired with shoes
• Playlist suggestions
Informational & Sorting: Informs recommendation engines and AI assistants. Supports sorting listings by edge attributes (such as score).
cross_sellCommercial Add-on / Accessory
• Phone suggesting a case or charger
• Software subscription suggesting an add-on seat
Informational: Used by shopping carts and AI checkout assistants to suggest relevant add-ons.
prerequisiteStrict Dependency
• Course requiring introductory course
• Milestone requiring prerequisite tasks
Enforced (Cycle Prevention): The platform automatically enforces a Directed Acyclic Graph (DAG). Linking records in a circular dependency (A→B→AA \rightarrow B \rightarrow A) is automatically rejected with a 422 Unprocessable Entity error.
alternativeSubstitute / Fallback
• Out-of-stock product replacements
• Dietary swaps (almond milk for dairy milk)
• Interchangeable mechanical spare parts
Behavioral: Enables fallback resolvers when a primary item is unavailable or out of stock.
referenceKnowledge Cross-Reference / “See Also”
• Related articles or documentation
• Research citations and wiki topic links
Informational: Enables multi-hop knowledge walks and GraphRAG exploration for AI agents.
assignmentOperational Peer Pairing
• Doctor assigned to patient
• Academic advisor assigned to student
Access Control: Works directly with data access rules to grant permissions based on active assignments.
compatibilityInteroperability / Fitment
• Software plugin compatibility with host apps
• Automotive brake pads matching vehicle models
Validation: Informs compatibility checks across cart items or component setups.
customDomain-Specific Extensibility
• Niche domain pairings (e.g., wine vintage affinity)
Requires specifying a descriptive customNature label.

You can control whether the connection is one-way or bidirectional:

  • directed (Default): The relationship flows from source to target. If Menu Item A lists Menu Item B as a pairing, Menu Item B does not automatically list Menu Item A unless explicitly linked.
  • mutual: The relationship is reciprocal. Linking Item A to Item B automatically makes Item B link back to Item A. When querying either entity, the connected peer is returned.

Custom Relationship Attributes (Edge Properties)

Section titled “Custom Relationship Attributes (Edge Properties)”

Real-world relationships often carry contextual data:

  • A dish pairing might have a pairing score (0.95) and a sommelier note (“Cuts through spicy salsa”).
  • A prerequisite might have a minimum grade requirement (“B+”).
  • A doctor-patient assignment might have an assigned date and primary care flag.

In API Now, you do not need to create a dedicated junction entity to store this data. Instead, define relationship attributes directly on the reference in the Domain Modeler:

  1. Open the association details for your connection (in the UI, associations are listed as References).
  2. Navigate to the Association Semantics section in the details panel.
  3. In the Peer relation list item where the semantic is added, click the Add property button located between the semantic label and the Configure button.
  4. A new field is added in the entity editor directly under the Reference item.
  5. Click on this new field to open the regular property editor to configure its name and type (such as a numeric score or text note). Relationship attributes support standard scalar types, while options not applicable to junction tables (such as primary keys, unique constraints, and indexing) are automatically omitted.

The platform automatically provisions these attributes on the underlying link table and includes them in sub-resource API payloads.


Associations tagged with PeerRelation are exposed as clean Sub-Resource endpoints in the API Modeler.

1. Link Records (POST .../{subResourcePath})

Section titled “1. Link Records (POST .../{subResourcePath})”

To establish a link between two existing records, send a POST request to the sub-resource endpoint with the target record’s ID and any relationship attributes:

POST /api/v1/menus/menu_horchata/pairings
Content-Type: application/json
Authorization: Bearer <token>
{
"menuId": "menu_carne_asada",
"score": 0.95,
"note": "Cuts through spicy salsa"
}

Response (201 Created):

{
"data": {
"id": "menu_carne_asada",
"name": "Carne Asada Taco",
"price": 350,
"score": 0.95,
"note": "Cuts through spicy salsa"
}
}

2. Automatic Cycle Detection (422 Unprocessable Entity)

Section titled “2. Automatic Cycle Detection (422 Unprocessable Entity)”

When nature: 'prerequisite', the runtime automatically checks for dependency loops before writing to the database. If Course B is already a prerequisite for Course A, attempting to link Course A as a prerequisite for Course B fails immediately:

{
"errors": [
{
"field": "targetId",
"message": "Cyclic dependency detected: linking 'course_B' to 'course_A' would create an invalid loop.",
"code": "E_CYCLIC_DEPENDENCY"
}
]
}

3. List Linked Peers (GET .../{subResourcePath})

Section titled “3. List Linked Peers (GET .../{subResourcePath})”

Fetching linked peers returns the associated records with their edge properties seamlessly attached:

GET /api/v1/menus/menu_horchata/pairings

Response (200 OK):

{
"data": [
{
"id": "menu_carne_asada",
"name": "Carne Asada Taco",
"score": 0.95,
"note": "Cuts through spicy salsa"
}
],
"meta": {
"total": 1
}
}

4. Update Relationship Attributes (PATCH .../{subResourcePath}/{targetId})

Section titled “4. Update Relationship Attributes (PATCH .../{subResourcePath}/{targetId})”

To modify relationship attributes without altering the underlying entities:

PATCH /api/v1/menus/menu_horchata/pairings/menu_carne_asada
Content-Type: application/json
{
"score": 0.98
}
Section titled “5. Unlink Records (DELETE .../{subResourcePath}/{targetId})”

Breaking a relationship removes the link from the link table. Both entities remain completely intact in their respective primary tables:

DELETE /api/v1/menus/menu_horchata/pairings/menu_carne_asada

PeerRelation represents independent connections. This enforces clear operational boundaries:

  • Pre-existing records: Both records must exist before they can be linked.
  • No nested creation: Top-level creation endpoints (POST /menus) do not accept inline arrays of peer items. Linking occurs explicitly via the sub-resource endpoint (POST /menus/{id}/pairings).
  • No cascading deletions: Unlinking records never deletes the target record from the database.

Embedded Hydration (schema.embedded) is 1:1 Only

Section titled “Embedded Hydration (schema.embedded) is 1:1 Only”

In API Now, schema.embedded: true is intentionally reserved for single (1:1) associations (such as inlining an address object on an order).

For multi-valued relationships (both 1:N collections and M:N peer relations), data is accessed via paginated sub-resource routes. This prevents unbounded query loops, ensures predictable performance, and guarantees that security rules are evaluated for every retrieved item.

Connecting two records verifies permissions across both sides:

  1. The user must have write permission on the parent resource.
  2. The user must have at least read/link permission on the target resource.