在 PHP 中自动记录 REST API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5315524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto documenting REST API in PHP
提问by Greywire
phpDocumentor seems to be the standard for documenting PHP code, though I have to wonder why it hasn't been updated in years..?
phpDocumentor 似乎是记录 PHP 代码的标准,但我想知道为什么它多年来没有更新......?
However, it does not seem suitable for documenting the entry points for a REST API; IE, externally accessible entry points that an end user of your system would be interested in, as opposed to documenting all the internal classes and such - something only of interest to the developers of the api.
但是,它似乎不适合记录 REST API 的入口点;IE,您的系统的最终用户会感兴趣的外部可访问入口点,而不是记录所有内部类等 - 只有 api 开发人员感兴趣的东西。
I am looking for something where I could say, hey this method here is externally accessible through REST at this URL, here's the GET or POST arguments it takes, it supports GET/POST/etc HTTP methods, it returns JSON or XML or whatever.
我正在寻找可以说的东西,嘿,这里的方法可以通过 REST 在这个 URL 外部访问,这是它需要的 GET 或 POST 参数,它支持 GET/POST/etc HTTP 方法,它返回 JSON 或 XML 或其他任何东西。
This information would be able to produce an API document. It could also be used by the code internally to automatically filter inputs, validate output, create basic unit tests, etc.
此信息将能够生成 API 文档。它也可以被代码内部使用来自动过滤输入、验证输出、创建基本单元测试等。
回答by fehguy
I know of 3 PHP integrations with swagger:
我知道 3 个 PHP 与 swagger 的集成:
All should help auto-create a swagger-spec, which gives you access from swagger-ui. Then you can generate api clients, etc.
所有这些都应该有助于自动创建一个 swagger-spec,它使您可以从 swagger-ui 访问。然后就可以生成api客户端等了。
回答by Kevin Ard
I found a great node package named apidocthat does an awesome job at doc-ing RESTfuls. It allows tons of API-specific tags to do with params and things like that, but what really sold me is its generated, in-doc test forms for each method.
我发现了一个名为apidoc的优秀节点包,它在文档化 RESTfuls 方面做得非常出色。它允许大量特定于 API 的标签处理参数和类似的事情,但真正卖给我的是它为每种方法生成的文档内测试表单。
I use it in my devops skeleton project at https://github.com/ardkevin84/devops.skel.php-with-docs-metrics, but you can see actualoutput in my callloop api project at https://github.com/ardkevin84/api.callloop. The apidoc index is build/api-docs/apidoc/index.html
我在https://github.com/ardkevin84/devops.skel.php-with-docs-metrics 的devops 框架项目中使用它,但您可以在https://github.com 的callloop api 项目中看到实际输出/ardkevin84/api.callloop。apidoc 索引是 build/api-docs/apidoc/index.html
The only downside, if it is one, is that it - naturally - takes its own docblocks. It doesn't clash with 'native' Docblocks, though. The apidoc blocks don't need to precede a method, so I generally group them together at the top of my endpoint file where the other doc engines won't associate them with a class doc.
唯一的缺点,如果有的话,就是它 - 自然地 - 需要自己的文档块。不过,它与“原生”Docblocks 并不冲突。apidoc 块不需要在方法之前,所以我通常在我的端点文件的顶部将它们组合在一起,其他文档引擎不会将它们与类文档相关联。
A byproduct: this works greatwith facades; I use facade and factory a lot in my endpoints, and the apidoc parser lets me handle the facade conditions separately. In the example below, 'subscribe', 'unsubscribe', and 'trigger' are handled by a single entry-point, but they're documented separately.
一个副产品:这个作品伟大与外墙; 我在端点中经常使用 Facade 和 factory,并且 apidoc 解析器让我可以分别处理 Facade 条件。在下面的示例中,“订阅”、“取消订阅”和“触发”由单个入口点处理,但它们是单独记录的。
Example: This Docblocks
示例:此文档块
/**
* @api {get} ?action=:action&first=:firstname&last=:lastname&email=:useremail&phone=:phone&gid=:groupid Subscribe
* @apiSampleRequest http://www.example.com/rest/callloop.php
* @apiName Subscribe
* @apiGroup Subscription
* @apiDescription subscribes a user to the provided group
* @apiParam {string="subscribe","unsubscribe","trigger"} action=subscribe API Action to call. For subscriptions, use "subscribe"
* @apiParam {String} [first] Optional first name
* @apiParam {String} [last] Optional last name
* @apiParam {String} [email] Optional user email
* @apiParam {String} phone User's mobile phone number
*/
is required to generate this output, complete with the test form
important, if you are using standard $_GET with query params:The package that's installed from node doesn't support enpoints like service.php?param=value
, but there's a pull request in the git repo at https://github.com/apidoc/apidoc/pull/189which addresses this. It's a basic fix to the default template. I patched the few lines into my node package and it works like a charm.
重要的是,如果您使用带有查询参数的标准 $_GET:从节点安装的包不支持像 那样的端点service.php?param=value
,但是在https://github.com/apidoc/apidoc/pull/的 git 存储库中有一个拉取请求189解决了这个问题。这是对默认模板的基本修复。我将几行修补到我的节点包中,它就像一个魅力。
shameless self-promotion:This is probably much easier to use under an automated build. Check out my devops project above for a kickstart ;) It's forked from jenkins-php, but adds in several doc engines and stub targets for things like pushing generated docs\metrics to a localhost path and packaging output for release (zip, tar, etc)
无耻的自我推销:这在自动构建下可能更容易使用。查看上面我的 devops 项目以获取启动项 ;) 它是从 jenkins-php 分叉出来的,但添加了几个文档引擎和存根目标,例如将生成的 docs\metrics 推送到本地主机路径和打包输出以供发布(zip、tar 等) )
回答by alganet
A RESTful API should be entirely discoverable and auto-documented. You only need an URL and everything else linked to it should describe itself. Sounds like an utopia, but it's feasible.
RESTful API 应该是完全可发现和自动记录的。您只需要一个 URL,链接到它的所有其他内容都应该描述自己。听起来像一个乌托邦,但它是可行的。
For example, let's start out with a stackoverflow-like sample URL: http://restfuloverflow.com(illustrative)
例如,让我们从一个类似 stackoverflow 的示例 URL 开始:http: //restfuloverflow.com(说明性的)
The first thing you do on a RESTful resource is an OPTIONS request. You always need to include an Accept header to instruct the server to respond to the most appropriate mime type:
您对 RESTful 资源执行的第一件事是 OPTIONS 请求。你总是需要包含一个 Accept 头来指示服务器响应最合适的 mime 类型:
OPTIONS * HTTP/1.1
Accept: text/html, text/xml, application/json
Host: restfuloverflow.com
The server should instruct the client on what is possible to do on that URL:
服务器应该指示客户端可以在该 URL 上做什么:
HTTP/1.1 200 Ok
Allow: GET, POST, PUT, DELETE, OPTIONS, TRACE, PATCH
This is the RESTful API telling you that this service support these methods. The first one you'll try is something like the request below. An user hitting the API with a browser should work in a similar way.
这是 RESTful API,告诉您该服务支持这些方法。您将尝试的第一个类似于下面的请求。使用浏览器点击 API 的用户应该以类似的方式工作。
GET / HTTP/1.1
Accept: text/html, text/xml, application/json
Host: restfuloverflow.com
The server then should return some links pointing to related resources, if available:
如果可用,服务器应该返回一些指向相关资源的链接:
HTTP/1.1 200 Ok
Content-Type: text/xml
<?xml version="1.0">
<qa>
<link href="/questions" title="Questions"/>
<link href="/tags" title="Tags"/>
<link href="/users" title="Users"/>
</qa>
An HTML version should use <a>
links, and JSON responses should use JSON-Schema links
attribute.
HTML 版本应使用<a>
链接,而 JSON 响应应使用 JSON-Schemalinks
属性。
Let's say the client now decides that it wants to know what to do with questions:
假设客户现在决定它想知道如何处理问题:
OPTIONS /questions HTTP/1.1
Host: restfuloverflow.com
Accept: text/html, text/xml, application/json
A possible response could be:
一个可能的回应可能是:
HTTP/1.1 200 Ok
Allow: GET, POST
Content-Type: text/xml
<?xml version="1.0">
<xsd:element name="question">
<!-- XML Schema describing a question -->
</xsd:element>
Well, the server told us that it's possible to GET and POST a new question. It also told us how a question in XML looks like by providing a XML Schema. A JSON-SCHEMA could be provided for JSON, and in HTML a form for new questions could be provided.
好吧,服务器告诉我们可以 GET 和 POST 一个新问题。它还通过提供 XML 模式告诉我们 XML 中的问题是什么样的。可以为 JSON 提供 JSON-SCHEMA,并且可以在 HTML 中提供用于新问题的表单。
Let's say the user wants to GET questions:
假设用户想要 GET 问题:
GET /questions HTTP/1.1
Host: restfuloverflow.com
Accept: text/html, text/xml, application/json
Then the server responds:
然后服务器响应:
HTTP/1.1 200 Ok
Content-Type: text/xml
<?xml version="1.0">
<questions>
<link href="/questions/intersting" title="Intersting Questions"/>
<link href="/questions/hot" title="Hot Questions"/>
</questions>
Now, everything is linked again. The thing keeps going in a way that the service describes itself. The Netflix APIfollows similar principles, but lacks some auto-discover features.
现在,一切又重新联系起来。事情继续以服务描述自己的方式进行。在Netflix的API遵循类似的原则,但缺少一些自动发现功能。
This Brazillian Government APIdescribes itself using RDF. It's one of the best RESTful samples I've ever seen. Try changing .rdf to .xml, .json or .html. (It's all in Portuguese, sorry for that).
这个巴西政府 API使用 RDF 描述自己。这是我见过的最好的 RESTful 示例之一。尝试将 .rdf 更改为 .xml、.json 或 .html。(都是葡萄牙语,抱歉)。
The best tool for RESTful APIs in PHP is Respect\Rest. It has most of the workflow I've described here already bootstrapped, and new features are coming (It's still in 0.4x version).
PHP 中 RESTful API 的最佳工具是Respect\Rest。它具有我在此处描述的大部分工作流程已经引导,并且新功能即将推出(它仍然是 0.4x 版本)。
The cost of building a documenting system for RESTful applications is the same as building a RESTful application. This is why there are so few tools like that, and usually they're not that good.
为 RESTful 应用程序构建文档系统的成本与构建 RESTful 应用程序的成本相同。这就是为什么像这样的工具很少,而且通常它们不是那么好。
回答by RVN
Swagger seems promising but it will require your API expose itself in a compatible manner... it is quite nice, however, with a test console, etc all built-in... you can download a javascript version and run it on your server alongside the php api.
Swagger 看起来很有前途,但它需要你的 API 以兼容的方式暴露自己......但是,它非常好,带有测试控制台等所有内置......你可以下载一个javascript版本并在你的服务器上运行它与 php api 一起。
EDIT: here is the link, it isnt so easy to find on google if you dont have the full name... lol... Swagger-UI: https://github.com/wordnik/swagger-ui
编辑:这是链接,如果你没有全名,在谷歌上很难找到......大声笑...... Swagger-UI:https: //github.com/wordnik/swagger-ui
回答by Ian Selby
The easiest thing to do is use a docblock tokenizer / parser. There are a couple of them out there (I'll plug mine shortly), but basically they can examine the docblock and tokenize any custom (or non-custom) docblock tags. I've use this inside a framework of mine to define view helper types via a tag called "@helperType".
最简单的方法是使用 docblock 标记器/解析器。那里有几个(我很快就会插入我的),但基本上他们可以检查 docblock 并标记任何自定义(或非自定义)docblock 标签。我已经在我的框架中使用它通过名为“@helperType”的标签来定义视图助手类型。
Like I said, there are plenty out there, but here's mine to get you started: https://github.com/masterexploder/DocumentingReflectionMethod
就像我说的,那里有很多,但这里有我的帮助你开始:https: //github.com/masterexploder/DocumentingReflectionMethod
Basically, use something like that and you can use it to both generate your docs, and to do stuff like auto filtering, validation, etc.
基本上,使用类似的东西,您可以使用它来生成文档,并执行自动过滤、验证等操作。
As far as unit test creation, PHPUnit can generate those automatically from your classes (check their docs for more info: http://www.phpunit.de/manual/3.5/en/skeleton-generator.html#skeleton-generator.test
至于单元测试的创建,PHPUnit 可以从您的类中自动生成这些(查看他们的文档以获取更多信息:http: //www.phpunit.de/manual/3.5/en/skeleton-generator.html#skeleton-generator.test
You can also have phpdocumenter parse your custom tags: http://manual.phpdoc.org/HTMLSmartyConverter/default/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#using.command-line.customtags
您还可以让 phpdocumenter 解析您的自定义标签:http://manual.phpdoc.org/HTMLSmartyConverter/default/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#using.command-line.customtags
Finally, there is one framework out there (that I know of, I'm sure there are tons) that uses annotations to do all sorts of restful goodness (perhaps saving yourself some work): https://github.com/recess/recess
最后,有一个框架(我知道,我确信有很多)它使用注释来做各种宁静的好事(也许可以为自己节省一些工作):https: //github.com/recess/休息时间
Hope that helps!
希望有帮助!