使用 PHP 创建 REST API [英] Creating a REST API using PHP

查看:44
本文介绍了使用 PHP 创建 REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建我的第一个 API,如果传递两个值,我应该得到 JSON 格式的响应.该数字将通过 POST 作为参数传递.使用 cURL 或任何可用的 POST 方法.

I’m creating my first API to which if two values are passed, I should get the response in the JSON format. The number will be passed as parameters by POST. Either using cURL or whatever POST method is available.

尽管这是一个非常基本的方法,但我想知道最佳实践,并且 API 应该以模型-控制器为基础创建.不仅仅是普通的 PHP.

Even though this is a very basic one, I would like to know the best practices and the API should be created by model–controller basis. Not just plain PHP.

我在 Google 上搜索了许多 REST API 教程.他们很好,我已经获得了一些相关知识.

I have Googled for many REST API tutorials. They were good and I have acquired some knowledge on it.

但我想获得代码的示例模型,以便我可以参考它并构建我自己的模型,当然,该示例符合制作真正 REST API 的标准做法.

But I would like to get a sample model of the code so that I can refer to it and build my own, and that sample of course in the standard practice of making a real REST API.

如果你问我尝试过什么,那真的很有趣,作为初学者,我能做的就是:

If you ask me what I have tried, it would be really fun, as a beginner, all I could do is this:

$num1 = $_REQUEST['num1'];
$num2 = $_REQUEST['num2'];

$total = $num1 + $num2;
echo json_encode($total);

当然这永远不能称为 API,但仍然如此.如果我对此给出 POST 响应,我希望来自 REST API 的响应为 JSON.我也应该能够通过 REST 控制台对其进行测试,以便获得标准响应.

Of course this can never be called an API, but still. If I give a POST response to this, I want the response from the REST API as JSON. I should be able to test it by REST console as well so that I get a standard response.

请为我提供一个非常基本但又标准的 RESTful API.

Please do provide me with a very basic but yet a standard RESTful API.

推荐答案

在您的示例中,这很好:它既简单又有效.我唯一建议的是:

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. 验证发布的数据
  2. 确保您的 API 正在发送 Content-Type 标头以告诉客户端期待 JSON 响应:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

header('Content-Type: application/json');
echo json_encode($response);

除此之外,API 是接受输入并提供输出的东西.有可能过度设计"事物,因为您会使事情变得更复杂.

Other than that, an API is something that takes an input and provides an output. It’s possible to "over-engineer" things, in that you make things more complicated that need be.

如果您想沿着控制器和模型的路线走下去,请阅读 MVC 模式 并确定您的域对象如何适应它.看看上面的例子,我可以看到一个带有 add() 动作/方法的 MathController.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

GitHub 上有几个 RESTful API 的起点项目,值得一看.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

这篇关于使用 PHP 创建 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆