如何在API Blueprint中定义固定长度数组?以location属性(长度2)为例
Hey there! I’ve run into this exact need before when building API specs with API Blueprint and using Apiary for documentation. Let me walk you through the correct way to enforce a fixed-length 2-element array for your location property.
The Problem with Your Current Syntax
Your current line + location (array[number], required) tells Apiary that location is a required array of numbers, but it doesn’t set any constraints on how many elements it should contain. That’s why you’re seeing the generic "0" placeholder in the interface—without explicit length rules, Apiary just shows a default empty array preview.
The Solution: Use MSON to Enforce Fixed Length
API Blueprint uses MSON (Markdown Syntax for Object Notation) to add detailed schema constraints. To make your location array exactly 2 elements long, you need to define both minItems and maxItems as 2. Here’s how to write it:
+ location (array[number], required) + Attributes + minItems: 2 + maxItems: 2
Alternatively, you can use a more concise shorthand if you prefer:
+ location (array[number], required) + Length: 2
What This Does in Apiary
Once you add these constraints:
- The interface will no longer show a generic "0" placeholder—instead, it’ll display two number fields (matching your fixed length requirement).
- Apiary will validate any example requests/responses to ensure
locationhas exactly 2 elements. - Your documentation will clearly communicate to consumers that this array must always have two numeric values (like latitude and longitude, I assume!).
Quick Note on the "0" Interface Element
That "0" you saw is just Apiary’s default way to let you add array elements manually in the editor preview. But to make the requirement official in your spec, you need to include the MSON length constraints as above—this is the only way to enforce the fixed length in both the documentation and any validation.
内容的提问来源于stack exchange,提问作者Elias Garcia

