使用php创建api [英] create api using php

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

问题描述

我想用php开发一个简单的api.

I want to develop one simple api using php.

我的功能是,如果有人输入一些所需的值,那么他们将从我网站旁边的算法中获得计算结果.

My functionality is that if some one enter some required values then they will get calculation result from the algorithm beside on my site.

我不知道从哪里开始.并且也没有获得任何使用 PHP 的 API 示例代码.

I am not getting from where can i start. and also not getting any sample code for API using PHP.

推荐答案

听起来您想要创建一个网络服务,其他人可以连接到它,发送答案并检索结果.

It sounds like you want to create a web-service that other people can connect to, send answers and retrieve a result.

如果是这样,您有三个选项,SOAP、XML-RPC 和 REST.如果它是一个简单的 API,那么 SOAP(可能还有 XML-RPC)就显得过分了——您不想创建 WSDL 文件,安装一个 SOAP 服务器库(尽管 Zend_Soap 已经足够了).另一方面,REST 将允许任何人轻松使用您的 API.

If that's the case, you've got three options, SOAP, XML-RPC and REST. If it's a simple API, SOAP (and probably XML-RPC) will be overkill - you don't want to have to create a WSDL file, install a SOAP server library (although, Zend_Soap is decent enough). REST on the other hand will allow anyone to easily consume your API.

让我们看一个例子,假设你想提供一个简单的求和"服务(即添加几个数字),你可以有一个这样的 URI 方案:

Let's look at an example, say you want to provide a simple "sum" service (i.e., add a few numbers), you could have a URI scheme like this:

http://example.com/sum

将数字 5、8 和 9 相加,您的 Web 服务用户只需执行 HTTP GET 即可

to sum the numbers 5, 8 and 9 your web service users would simpy execute an HTTP GET to

http://example.com/sum/5/8/9

让我们暂时假设求和实际上是一项计算成本非常高的任务,通过使用 REST 和 GET,您可以利用 HTTP 缓存,这样当有人发送相同的计算参数时,您的服务器不会经常受到攻击.

let's pretend for a moment that summing is actually a very computationally expensive task, by using REST and a GET you can take advantage of HTTP caching so that your server isn't constantly hit when someone sends the same parameters for calculation.

如果您的 Web 服务具有非无副作用的资源(即它更改了数据库中的某些内容),您应该使用 PUT、POST 或 DELETE(PUT 用于更新,POST 用于创建,DELETE 用于删除)作为HTTP 规范声明 GET 不应有副作用.同样,如果返回错误或网络连接超时,重复 PUT 和 DELETE 应该是安全的.

If your web service has a resource that isn't side-effect free (i.e. it changes something in a database) you should use PUT, POST or DELETE (PUT for updates, POST for creating and DELETE for delete) as the HTTP specs state the GETs shouldn't have side-effects. Similarly, PUT and DELETE should be safe to repeat if you get an error back or the network connection times out.

这里有关于 REST 的精彩演讲(视频和幻灯片):http:///www.parleys.com/display/PARLEYS/Home#talk=31817742

There's a good talk (video and slides) on REST here: http://www.parleys.com/display/PARLEYS/Home#talk=31817742

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

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