說明
API Blueprint is simple and accessible to everybody involved in the API lifecycle. Its syntax is concise yet expressive. With API Blueprint you can quickly design and prototype APIs to be created or document and test already deployed mission-critical APIs
通俗一點就是一種接口規范,而且是使用markdown的,使用markdown的語法書寫接口。
背景
目前和前端聯調、其他部門聯調使用的方式有:
使用MarkDown出接口文檔,放在共同的gitlab倉庫上面,前后端都可以訪問(只要約定好誰修改就好了,避免兩個人都修改出現差異),作為一個經常寫方法注釋的好程序員來說(其實你的leader也會要求你),要在每一個接口上面寫上幾行方法注釋,注明這個方法是做啥的,不然別人接手不便捷 _;
使用apiDoc工具(使用方法可以查看:http://birjemin.com/wiki/php-apidoc),將相應的接口規范以注釋的方式寫在每一個方法上面,然后生成相應的apiDoc文檔(只需要寫一下注釋,不需要再寫接口文檔啦),通過node服務搭建一個服務環境,前端直接訪問我的開發機進行查看啦
使用
birjemin/blueprint
+aglio
/macdown
...組合,比如在接口的方法上面按照一定的格式進行注釋,然后使用該composer包生成apib文件,這個文件是一個遵循blueprint接口規范的markdown文件。可以使用aglio插件搭建一個web服務(這個插件支持實時更新,不需要刷新頁面),也可以使用macdown編輯器查看這個文件。
搭建步驟
1.安裝aglio(npm是啥???自己問前端同學吧。。)
npm install -g aglio
請檢查是否安裝成功。
2.給laravel項目引入composer包(包已經提交,不過國內鏡像還沒同步)
composer require birjemin/blueprint dev-master
or
composer require birjemin/blueprint
3.在app.php
中添加BlueprintServiceProvider::class
4.給接口添加注釋,添加在Controller入口方法前面(詳細的注釋方式請查看https://github.com/dingo/api/wiki/API-Blueprint-Documentation)。
/**
* Class CarsController
* @package App\Http\Controllers
* @Resource("CarResource", uri="/api/cars")
*/
class CarController extends Controller
{
/**
* cars list
*
* Get current cars list
*
* @Get("/list")
* @Transaction({
* @Request(identifier="page=1&type=1"),
* @Response(200, body={"msg": "返回成功","code": 200,"page": 1,"timestamp": "1522673813","data":{"result":[{"price": "2200","type": "福特","notice": "豪車"},{"price": "2200","type": "大眾","notice": "車"}]}})
* })
* @Parameters({
* @Parameter("page", type="integer", required=true, description="分頁", default=1),
* @Parameter("search", type="string", required=false, description="搜索條件"),
* @Parameter("type", type="integer", required=true, description="汽車類型", default=1, members={
* @Member(value="1", description="新車"),
* @Member(value="2", description="舊車")
* })
* })
*/
public function index()
{
return json_decode('{"succ":true,"code":0,"message":"","data":{"result":true}})');
}
}
@Response(200, body={...}
中的[
和]
要替換成{
和}
,這里不替換是因為我的博客使用了jekyll
,github報錯啦~~
5.創建apib
文件
php artisan birjemin:docs --output-file=tianming.apib
項目下面生成了tianming.apib文件,這個是一個markdown文件,可以直接用markdown編輯器打開,下面講一下aglio的web服務。
6.運行aglio服務(詳細的命令可以去https://github.com/danielgtaylor/aglio查看)
aglio -i tianming.apib -s
7.訪問:http://27.0.0.1:3000
(端口可以自定義,這個是默認的)
注意點
1.返回的數據不可以json如果是數組,{}
代替[]
這個符號,比如示例中的。
{"msg": "返回成功","code": 200,"page": 1,"timestamp": "1522673813","data":{"result":[{"price": "2200","type": "福特","notice": "豪車"},{"price": "2200","type": "大眾","notice": "車"}]}}
就要將里面的中括號替換成大括號!
2.這些注釋寫錯了會報錯哦~
3.和apidoc的注釋有區別~~
補充文檔
- https://apiblueprint.org/
- https://github.com/danielgtaylor/aglio
- https://github.com/dingo/api/wiki/API-Blueprint-Documentation