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

查看:212
本文介绍了使用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.

我有许多REST API教程的Googled。他们是好的,我已经获得了一些知识。

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);


获取输入并提供输出。

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模式上阅读并编写你的域对象如何适应它。看看上面的例子,我可以看到一个 MathController 和一个 add()操作/方法。

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天全站免登陆