RAML v0.8主文件api.raml引用子资源文件问题求助
哥们,我帮你捋清楚怎么正确创建这个RAML主文件,之前踩过的坑我都懂,RAML v0.8里有两种靠谱的方式来整合你的animals.raml和plants.raml资源,既能让API使用者方便导航到子文件,也能直接在主页面内联展示,再也不会报错了:
方式一:通过!include引用实现导航(推荐模块化设计)
这种方式保持子RAML文件的独立性,主文件只做入口概览,RAML解析器会自动生成可跳转的链接,用户点击就能查看子资源的详细定义。
主文件api.raml的写法:
# %RAML 0.8 --- title: 生物API概览 baseUri: http://api.example.com/v1 version: v1 # 引用同目录下的子RAML文件,用户可点击导航到对应资源详情 /animals: !include animals.raml /plants: !include plants.raml
关键注意事项(避免报错):
- 子文件
animals.raml和plants.raml不要包含RAML头部声明(也就是不要写# %RAML 0.8和---),只需要写资源的具体定义,比如animals.raml应该是这样:description: 动物资源集合,支持查询、新增等操作 get: description: 获取所有动物列表 responses: 200: body: application/json: example: | [{"id": 1, "name": "东北虎", "category": "哺乳类"}, {"id": 2, "name": "丹顶鹤", "category": "鸟类"}] post: description: 新增一只动物 body: application/json: schema: | { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": {"type": "string"}, "category": {"type": "string"} }, "required": ["name"] } responses: 201: description: 动物创建成功 - 确保子文件和主文件在同一目录,或者使用正确的相对路径(比如
./api-resources/animals.raml) - 缩进严格用空格(不要用Tab),YAML对缩进非常敏感,缩进错误会直接导致解析报错
方式二:直接内联子资源内容(适合小型API)
如果希望所有资源定义都在主页面展示,不需要跳转,可以把子RAML里的内容直接复制到api.raml中:
主文件api.raml的写法:
# %RAML 0.8 --- title: 生物API概览 baseUri: http://api.example.com/v1 version: v1 /animals: description: 动物资源集合,支持查询、新增等操作 get: description: 获取所有动物列表 responses: 200: body: application/json: example: | [{"id": 1, "name": "东北虎", "category": "哺乳类"}, {"id": 2, "name": "丹顶鹤", "category": "鸟类"}] post: description: 新增一只动物 body: application/json: schema: | { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": {"type": "string"}, "category": {"type": "string"} }, "required": ["name"] } responses: 201: description: 动物创建成功 /plants: description: 植物资源集合,支持查询、新增等操作 get: description: 获取所有植物列表 responses: 200: body: application/json: example: | [{"id": 1, "name": "雪松", "category": "裸子植物"}, {"id": 2, "name": "牡丹", "category": "被子植物"}] post: description: 新增一株植物 body: application/json: schema: | { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "name": {"type": "string"}, "category": {"type": "string"} }, "required": ["name"] } responses: 201: description: 植物创建成功
这种方式的好处是用户打开api.raml就能看到所有资源的完整定义,不需要跳转,适合资源不多的小型API。
内容的提问来源于stack exchange,提问作者Radek Skokan
相关产品推荐
相关产品推荐

