2.1 RAML 1.0 Fundamentals, Data Types & Resource Hierarchy

Key Takeaways

  • API-led connectivity relies on an API-first, contract-first design paradigm using RAML 1.0 to define interface specifications before any backend implementation code is written.
  • A valid RAML 1.0 root document requires the '#%RAML 1.0' header as line 1 and must specify the mandatory 'title' property along with optional root facets such as 'version', 'baseUri', 'protocols', and 'mediaType'.
  • Resources represent nouns in a hierarchical tree (e.g., '/customers/{customerId}/orders'), where URI parameters identify specific entities, query parameters filter or paginate collections, headers carry metadata, and body payloads transport entity representations.
  • HTTP methods map to REST operations (GET for safe/idempotent reads, POST for non-idempotent creations, PUT for idempotent replacements, PATCH for partial updates, DELETE for idempotent removals) with standard HTTP status codes (200, 201, 204, 400, 401, 403, 404, 405, 500).
  • The RAML 1.0 type system supports primitives, object inheritance, arrays, unions (e.g., 'string | integer'), and fine-grained facets (minimum, maximum, minLength, maxLength, pattern, enum) for schema-level payload validation.
Last updated: August 2026

RAML 1.0 Fundamentals, Data Types & Resource Hierarchy

Designing robust, consistent, and consumable interfaces is the initial phase of the MuleSoft API development lifecycle. RAML (RESTful API Modeling Language) 1.0 is a non-proprietary, YAML-based modeling language that allows developers to describe RESTful APIs cleanly and unambiguously. Adopting an API-First, Contract-First methodology ensures that technical and business stakeholders validate interface contracts before backend implementation begins in Anypoint Studio.


1. API-First Design Principles & The Contract-First Lifecycle

In traditional "code-first" development, engineers implement backend endpoints and expose APIs as an afterthought. This produces tightly coupled integrations, unstandardized endpoints, and cascading rework when consumer requirements shift.

+---------------------------------------------------------------------------------------------------+
|                                 THE API-FIRST CONTRACT LIFECYCLE                                  |
|                                                                                                   |
|   [1. DEFINE]           [2. SIMULATE]          [3. VALIDATE]        [4. IMPLEMENT]                |
|   Design RAML 1.0  -->  Enable Mocking    -->  Share Prototype  --> Scaffold Flows with           |
|   Specification         Service in Cloud       with Consumers       APIkit in Anypoint Studio     |
|   (API Designer)        (Zero Backend Code)    (Collect Feedback)   (Generate Interface)          |
+---------------------------------------------------------------------------------------------------+

Advantages of Contract-First Design:

  1. Parallel Development: Consumer teams (e.g., mobile, frontend web) and provider teams (MuleSoft integration engineers) build concurrently against the agreed-upon contract using mock endpoints.
  2. Reduced Rework: Interface flaws, missing attributes, and awkward URI hierarchies are caught and resolved in API Designer before a single line of Mule flow logic or DataWeave transformation is written.
  3. Automated Governance: API design rules (naming conventions, security requirements, error structures) can be validated automatically before code implementation.

2. RAML 1.0 Document Root Specification

Every RAML document begins with a mandatory header line followed by root-level declarations that define the global metadata of the API.

#%RAML 1.0
title: OmniChannel Customer Experience API
version: v1
baseUri: https://api.enterprise.com/customer-exp/{version}
baseUriParameters:
  version:
    type: string
    example: v1
protocols: [ HTTPS ]
mediaType: [ application/json ]
documentation:
  - title: Overview
    content: |
      Welcome to the Customer Experience API. This API orchestrates customer
      profiles and transaction histories across mobile and web channels.

Essential Root Keys:

  • #%RAML 1.0: Mandatory. Must be the absolute first line of the document with no preceding characters or whitespace. Tells the parser which specification version to apply.
  • title: Mandatory. A human-readable string identifying the API (e.g., OmniChannel Customer Experience API).
  • version: Optional but best practice. Declares the API interface version (e.g., v1, v2.0).
  • baseUri: The target URI where the API is hosted. Can contain URI parameters such as {version}.
  • protocols: Array specifying supported transport protocols (HTTP, HTTPS). HTTPS is standard for enterprise security.
  • mediaType: Default payload MIME type for requests and responses across all resources unless overridden at the method level (e.g., application/json, [ application/json, application/xml ]).
  • documentation: Array of title/content pairs written in Markdown to render user-facing developer portal guides.

3. Resource Modeling & URI Hierarchy

Resources in RAML represent domain entities and collections. Resources must always be nouns (never verbs) and begin with a leading slash /.

+---------------------------------------------------------------------------------------------------+
|                                 REST RESOURCE HIERARCHY TREE                                      |
|                                                                                                   |
|   /customers                           <-- Collection Resource (All Customers)                    |
|       |                                                                                           |
|       +--> /{customerId}               <-- Member Item Resource (Specific Customer)               |
|                 |                                                                                 |
|                 +--> /orders           <-- Nested Sub-Collection Resource (Orders for Customer)   |
|                         |                                                                         |
|                         +--> /{orderId}<-- Nested Member Item Resource (Specific Customer Order)  |
+---------------------------------------------------------------------------------------------------+

RAML Hierarchy Representation:

/customers:
  get:
    description: Retrieve a paginated list of customers
  post:
    description: Register a new customer record

  /{customerId}:
    uriParameters:
      customerId:
        type: string
        pattern: ^CUST-[0-9]{5}$
        example: CUST-48201
    get:
      description: Retrieve details for a specific customer
    put:
      description: Replace all details for a specific customer
    delete:
      description: Remove a customer record

    /orders:
      get:
        description: Retrieve all orders belonging to the specified customer
      post:
        description: Submit a new order for this customer

4. Parameter Scoping: URI vs. Query vs. Headers vs. Body Payloads

Choosing the correct parameter type is a key competency tested on the developer exam:

+---------------------------------------------------------------------------------------------------+
|                                   PARAMETER CLASSIFICATION                                        |
|                                                                                                   |
|   [URI Parameter]       --> Identifies a specific entity in the path: /customers/{customerId}     |
|   [Query Parameter]     --> Filters, sorts, or paginates a collection: /customers?status=active   |
|   [Header Parameter]    --> Carries transport/security metadata: Authorization, X-Correlation-ID |
|   [Body Payload]        --> Carries entity state data for creation/update: { "name": "Jane" }     |
+---------------------------------------------------------------------------------------------------+
Parameter TypeRAML LocationPrimary Use CaseExample
URI ParameteruriParameters:Identifying a specific resource instance within the path hierarchy/{customerId} (CUST-1002)
Query ParameterqueryParameters:Filtering, searching, sorting, or paginating collection items?status=active&limit=25
Header Parameterheaders:Contextual metadata, auth tokens, correlation IDs, content negotiationAuthorization: Bearer xyz
Body Payloadbody:Entity payload data for state-changing operations (POST, PUT, PATCH){ "email": "user@org.com" }

RAML Parameter Definition Example:

/customers:
  get:
    headers:
      X-Correlation-ID:
        type: string
        required: false
        description: Unique UUID for end-to-end request tracing
    queryParameters:
      region:
        type: string
        required: false
        enum: [ NA, EMEA, APAC, LATAM ]
      tier:
        type: string
        required: false
        default: STANDARD
      limit:
        type: integer
        required: false
        minimum: 1
        maximum: 100
        default: 20

5. HTTP Methods, Idempotency & HTTP Status Codes

RESTful APIs leverage standard HTTP verbs to indicate the semantic intent of operations:

HTTP MethodSafe?Idempotent?Typical PayloadStandard Success CodeUse Case
GETYesYesNone200 OKRead resource or collection
POSTNoNoRequest Body201 CreatedCreate a new child resource
PUTNoYesRequest Body200 OK / 204 No ContentComplete overwrite/replacement of a resource
PATCHNoNo / Yes*Partial Body200 OKPartial modification of specific fields
DELETENoYesNone200 OK / 204 No ContentRemove an existing resource

[!NOTE] Safety vs. Idempotency:

  • Safe: An operation that does not alter resource state on the server (e.g., GET).
  • Idempotent: Making multiple identical requests produces the exact same server state as making a single request (e.g., GET, PUT, DELETE). POST is non-idempotent because 5 consecutive POST requests create 5 distinct records.

Core HTTP Status Codes in RAML Responses:

  • 200 OK: Successful retrieval or modification with response body.
  • 201 Created: Successful resource creation (typically returns Location header and newly created entity).
  • 204 No Content: Successful execution where no response body is returned (standard for DELETE or empty PUT).
  • 400 Bad Request: Client sent malformed JSON, invalid query parameters, or failed RAML type validations.
  • 401 Unauthorized: Client lacks valid authentication credentials (e.g., missing API key or expired JWT).
  • 403 Forbidden: Client is authenticated but lacks authorization/permission to access the resource.
  • 404 Not Found: Target resource URI does not exist.
  • 405 Method Not Allowed: Resource URI exists, but the requested HTTP verb is not supported (e.g., POST to a read-only endpoint).
  • 500 Internal Server Error: Unhandled Mule application exception or downstream backend outage.

6. The RAML 1.0 Data Type System

RAML 1.0 features an expressive type system that replaces external XML/JSON Schemas with clean, native YAML definitions declared under the root types: node or in external fragment files.

1. Primitive Types and Facets

RAML primitive types include string, number, integer, boolean, date-only (yyyy-MM-dd), time-only (HH:mm:ss), datetime-only (yyyy-MM-ddTHH:mm:ss), datetime (RFC3339/RFC2616), file, nil, and any.

types:
  CustomerIdentifier:
    type: string
    minLength: 8
    maxLength: 12
    pattern: ^CUST-[0-9]{4,8}$

  AccountBalance:
    type: number
    minimum: 0.00
    maximum: 10000000.00
    multipleOf: 0.01

  MembershipStatus:
    type: string
    enum: [ PROSPECT, ACTIVE, SUSPENDED, TERMINATED ]
    default: PROSPECT

2. Complex Object Types, Properties & Optionality

Properties are mandatory by default in RAML 1.0. To mark a property as optional, append ? to the property name or set required: false.

types:
  Address:
    type: object
    properties:
      street: string
      city: string
      state: string
      postalCode: string
      country?:
        type: string
        default: USA

  Customer:
    type: object
    properties:
      id: CustomerIdentifier
      firstName: string
      lastName: string
      email:
        type: string
        pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
      balance: AccountBalance
      status: MembershipStatus
      billingAddress: Address
      tags?: string[]                 # Array of strings
      createdAt: datetime

3. Array Types, Union Types & Type Inheritance

RAML 1.0 allows powerful type compositions:

types:
  # Array Type
  CustomerCollection:
    type: array
    items: Customer
    minItems: 0
    maxItems: 500

  # Union Type (can be either Type A OR Type B)
  ContactMethod:
    type: EmailContact | PhoneContact

  EmailContact:
    type: object
    properties:
      emailAddress: string
      isPrimary: boolean

  PhoneContact:
    type: object
    properties:
      phoneNumber: string
      phoneType:
        enum: [ MOBILE, WORK, HOME ]

  # Type Inheritance (Subtyping)
  AuditableEntity:
    type: object
    properties:
      createdBy: string
      createdAt: datetime
      updatedAt?: datetime

  Order:
    type: AuditableEntity            # Inherits createdBy, createdAt, updatedAt
    properties:
      orderId: string
      totalAmount: number
      items: OrderItem[]

4. Examples in RAML Specifications

Examples provide concrete payload data that the API Mocking Service and API Console use to simulate realistic interactions:

types:
  CustomerSummary:
    type: object
    properties:
      customerId: string
      fullName: string
      email: string
    example:
      customerId: CUST-99412
      fullName: Sarah Jenkins
      email: sjenkins@enterprise.com

7. Exam Watch: Core Developer Scenarios & Traps

[!IMPORTANT] Exam Rule 1: RAML Header Line Validity The first line of a root RAML specification must be #%RAML 1.0. If there are blank lines, comments, or leading spaces before #%RAML 1.0, the RAML parser in API Designer and APIkit will throw a fatal syntax parsing error.

[!WARNING] Exam Rule 2: Property Optionality vs Default Requirement In RAML 1.0, properties in an object type are required by default. If a property does not have a ? suffix (e.g., middleName?) or explicit required: false, any client payload omitting that property will be rejected by the APIkit router with an HTTP 400 Bad Request validation failure.

[!TIP] Exam Rule 3: Choosing Between PUT and PATCH When an exam scenario describes updating only the email or status of an existing record without sending all other customer fields, the correct REST method to design in RAML is PATCH. If the requirement specifies replacing the full record representation, choose PUT.

Test Your Knowledge

A developer is creating a RAML 1.0 specification for an Order Management API. The requirement states that the root specification must declare a default response format of JSON, enforce HTTPS, and define a root version parameter of 'v1'. Which RAML 1.0 root declaration correctly satisfies these requirements?

A
B
C
D
Test Your Knowledge

An API designer is specifying a REST resource in RAML 1.0 to retrieve transactions for a specific customer. Clients need to filter these transactions by transaction date range (startDate, endDate) and specify a maximum number of records to return. How should this resource and its parameters be modeled according to REST and RAML best practices?

A
B
C
D
Test Your Knowledge

A developer writes the following RAML 1.0 data type definition for a Customer Registration payload: types: NewCustomer: type: object properties: customerId: string email: string phoneNumber?: string loyaltyPoints: type: integer required: false tier: string When a client submits a POST request containing only 'customerId', 'email', and 'tier', what will occur during APIkit validation?

A
B
C
D
Test Your Knowledge

A developer needs to define a RAML 1.0 DataType facet for a 'nationalId' field such that it accepts only alphanumeric strings exactly 9 characters in length, starting with two uppercase letters followed by seven digits (e.g., 'AB1234567'). Which DataType definition correctly enforces this constraint?

A
B
C
D