doujiao2443 2017-01-16 22:10
浏览 17
已采纳

为网页构建API的正确方法[关闭]

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.

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊