I am using symfony. When I am creating web page that will also have an API how should I do It ? Difference between them is that API will return for example JSON string as response, but web page will return html/text response if I am not mistaken. So should I add some condition that if the URL will be api.something.com
then return JSON and if it will be something.com
then return html/text ? Or should I build separate controllers ? but they will be same with exception of returning object.
为网页构建API的正确方法[关闭]
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- duandu8202 2017-01-16 23:13关注
Best practices
It is better to separate domains, this way you can use RESTful best practices to build your API without interfering with your www urls. The security checks are different for an API than for a web request, it means that you need to build separate controllers as well to handle those checks properly.
For small projects
If you really want to use one controller for both usage (because you don't think your projet need to have the higher standards) you can check for a header in the request to distinguish an api call from a web request. For instance you could use the header
accept: application/json
for your api request.Example:
function isXmlHttpRequest() { return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'; } function isApiRequest() { return strtolower($_SERVER['HTTP_ACCEPT']) === 'application/json'; } if(isApiRequest() || isXmlHttpRequest()){ return $jsonResponse; }else{ return $webPage; }
Framework suggestion
Laravel framework is a good solution to make such web architecture. It helps you to separate domains and controllers in a simple and easy way. It has tools to help you build a RESTful architecture as well in no time. You can learn how to use it here.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 西门子S7-Graph,S7-300
- ¥50 用易语言http 访问不了网页
- ¥50 safari浏览器fetch提交数据后数据丢失问题
- ¥15 matlab不知道怎么改,求解答!!
- ¥15 永磁直线电机的电流环pi调不出来
- ¥15 用stata实现聚类的代码
- ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
- ¥20 docker里部署springboot项目,访问不到扬声器
- ¥15 netty整合springboot之后自动重连失效
- ¥15 悬赏!微信开发者工具报错,求帮改