I want to make an API in php. I searched a lot of tutorials. Every tutorial uses json_encode() to return a json format of an array.
This array is made from the data we get from database.
I also am familiar a restful api must follow all the constraints defined in the REST design to be called a restful.
I want to know.
We are using json_encode to send data in json form, and using HTTP. It is an restful api?
We also use all the time HTTP in PHP. So everything is already restful?
What separates an restful api from an normal API?
What things are necessary for an API in PHP to be called restful?
I know it's silly, but I am so confused. I already went through many tutorials.
REST runs on top of HTTP so you're most of the way there. What a REST API returns has nothing to do with REST and is more to do with the application's domain.
You're using json_encode to return JSON, which is fine and is perfectly acceptable as a REST return type. Another REST API might return a compressed CSV if bandwidth is tight or the device calling the API is resource constrained. What it returns is of less importance than how it's called.
REST refers to representation. So the client wants a representation of a resource at the server. e.g. this:
/api/user/{name}
can return the representation of a user in JSON format using json_encode. e.g.
/api/user/smith
returns:
{
"nane": "Mr. Smith",
"email: "smith#smith.com"
}
if you use the REST verbs to work with that state then you're using REST.
The other aspect of REST that causes lots of debate is what the URLs look like. The URLs should ideally identify a resource and the verbs say how that resource should be interacted with, e.g. GET a user, POST a new user, PUT updates to the existing user, DELETE an existing user.
The operations performed on the representation of the resource are specified by the HTTP methods.
To answer your question about "normal" APIs, there aren't any. There is no API standard, however REST provides those two markers, resources as URLs and operations on those resources as HTTP verbs. Other types of API are xml-rpc where some people use that type of URL, e.g. POSTing data to:
/api/user/new
the above isn't a RESTful URL as it doesn't identify a resource. It identifes an operation (new user).
SOAP is another type of API that is far more complex than REST but it was designed to do things REST doesn't need to do, such as routing and service discovery.
So in summary, if you expose your resources as URLs and use HTTP verbs to interact with them, you're using REST. Looks like you're good to go.
The main difference between REST and a HTTP API with JSON response is that REST uses
$_SERVER['REQUEST_METHOD'] values (POST/GET/PUT/DELETE) to differentiate between the create/read/update/delete actions. For an example, check out this small (66 line) program I've written to demonstrate the concept.
Related
I am currently working on a API Wrapper for an internal API. I have found a lot of answers when searching for how to test an API, but not an wrapper.
The problem is, that the API (of course) need authentication and is an internal API developed by another team.
The tests should be independent from the API itself and not really call teh API.
The tests need to work without a connection to the internal API, but I know, what valid requests from the class would look like, given a certain input.
My first thought was a solution, where I call an function of the API wrapper class and checking if the (curl) requests the class makes are equal to a predefined value. E.g. checking the JSON body of one or more POST requests is the same as I would expect.
How would you recommend implementing such a test?
Thanks a lot in advance for any help :)
Im confused regarding the need of REST for a web service.Im a noob when it comes to web service,the scalability etc.
This is my requirement
-Need to fetch some data eg:names of students in a class and their photographs plus their address and stuff
-There is no authenciation/Tokens required since the data is publicly available
My question is
-Do i need to use REST for this? Will MYSQL+PHP Webservice that communicates using HTTP GET and POST do the job?
-If i go with this approach will this affect the performance of the app,when there is bulk data and will it scale?The maximum number of users that may be using the app is just 50 at a time.
-Does REST offer significant advantages,since i dont know JSON and stuff,will it payoff the learning curve?
It's better to use REST. You can just post your data as HTTP or as JSON and then process this data in your function and return result as JSON .
I recommend you to use CakePHP or Yii because it's easy to use.
In case of bulk transaction you can use MongoDb as your database.
What I would say is that REST describes a way to leverage HTTP features and use them in an optimal way. Otherwise you don't have to use all the REST mechanisms to implement a RESTful application.
I think that this link could help you to understand how to implement a Web API (i.e. a RESTful application):
Designing a Web API: https://templth.wordpress.com/2014/12/15/designing-a-web-api/
Here are my answers to your questions:
REST doesn't require an authentication to access resources. However REST integrates authentication mechanisms based on the HTTP header Authorization.
REST describes good practices in using HTTP but of course, you're free to use it as you want ;-) REST recommends to use the HTTP methods for what they actually are. To be short, GET to retrieve data, PUT / POST to update data (POST mainly to add data and PUT to update them) and DELETE to delete data. POST can also be used for what we can see as actions. REST also uses specific URIs with path variables. If I use your example, the URI for a list of students within a class would be: /classrooms/<classid>/students. REST also define a mechanism to request specific content format such as JSON based on the header Accept. In fact, you're generally familiar with most of these aspects if you implement Web applications for some years and REST provides you a way to design your application to leverage them at best.
Regarding performance, I would say no. One of the key aspect of REST is that RESTful applications are stateless. No state must be handled on the server side. This allows applications to scale more readily. I don't see any reason for bad performances regarding bulk updates. In fact, it's up to you to handle them. REST leaves the choice of the data format content sent to the server and the way to handle them efficiently on the server side. You can consider using either synchronous and asynchronous approach. For the asynchronous approach, you should return an HTTP status code 202. This approach can allow you to control the work load of updates for concurrent users. You could add the bulk updates to a queue and handle them after one per one in a separate process or thread. An example of RESTful application that uses bulk updates is ElasticSearch. See this link: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.
The main advantage of REST is that it allows you to leverage HTTP mechanisms at best. Another thing that comes to mind is that there is now some tools allowing you to generate client kits to consume your application and generate documentations about the contract of your RESTful applications. See Swagger (Swagger, Swagger UI, Swagger Codegen) and RAML. These links can help you: http://swagger.io/ and http://raml.org/. Another tool, Restlet Studio (http://studio.restlet.com/#/), can help you to understand all these concepts since it comes with a sample application. Regarding the learning curve, I don't think that it's too much important since if you already implement web application, you know most of concepts.
Regarding the format you would use for content, JSON seems to be a good fit. However REST doesn't enforce any content kind. It provides a mechanism to request a specific content (Conneg, i.e. content negotiation based on the header Accept) but you don't have to use it. REST let you the way to manage this content within your application.
Hope it heps you,
Thierry
You can implement any protocol you want to do that, but using REST ensure you are following a common procedure which will make your application more maintainable.
The amount of resources used depends how do you implement the queries and responses on the server-side.
You should learn that, it will improve your knowledge as you can learn together other patterns (gateway, repository, MVC) to make your server-side professional and maintainable.
My suggestion for your application is implementing the server-side using a framework such as Laravel (I recommend), CakePHP or similar. I say that because your app seems to be just interaction with pre-defined models.
I'm asking this question because some of the websites is visited seems to be using a RESTful API to access the data even if it's on the website...
For example: my website will have 6 pages and 5 of them use the DB. But, I will also have a REST api for my partners...
So, the question is:
On my website, is it better to access directly the DB via mysqli_query or to use a RESTful API with Ajax calls to load data?
Just a note: I'll be using Zend Framework 2 for my RESTful API except if someone has a better option... I know Node.js and PHP... I'm able to write it in Ruby or something if it's better for me... Need a opinion on that...
Use the RESTful API.
The specification of REST is that we use the HTTP methods, which he calls verbs.(GET, POST, PUT, DELETE).
A direct request would be limiting it, or you would be using at most two method (verbs) - GET and POST.
For that you have to do this:
GET /user/frederick/edit
GET /user/frederick/update
GET /user/frederick/delete
GET /user/new
And with a RESTful API:
GET /user/frederick/
POST /user/new/
PUT /user/frederick/
DELETE /user/frederick/
The advantage of using your own API is that you don't have to write duplicate code. For example, you might have generate_for_rest and generate_for_server functions that do the same thing and just emit data in different formats. It's a good idea to reuse your own APIs as much as you can.
That said, I do find it a bit unusual that a website would communicate to itself with its own RESTful API. That requires an HTTP request (though it should be extremely fast) and conversion of the data twice. Instead it would make more sense to have an API that generates the data that you need and a facade that converts that data into formats for it to be used.
For example you could have a function get_all_users. Internally you can use get_all_users to get the results as php data structures that you can use immediately. In your controller that responds to HTTP requests you may do a JSON conversion, but you shouldn't be doing any duplicate work to get the data for either internal or external use.
This is a Homework task. It involves creating a simple DB and making CURL calls to the server to get results from the DB, accordingly I have a DBClass file with the required methods. I understand what REST architecture is in general, but I am kind of unable to put the pieces together. Here's what I have so far:
Model.class.php -> this is the Database class that instantiates connections to the DB and has methods that execute DB queries and return the result.
Simulator.php -> helper class, simulates HTTP requests (POST or GET only) to the localhost so my curl call is made to 'http://localhost/app/index.php'
index.php -> here is where I receive the CURL requests, in effect, I decode the HTTP requests to understand the request method, parameters, URI as such.
At this point, I am lost. Understandably a RESTful API request essentially is of the kind server/getMeMyBananas and getMeMyBananas is a DB method that looks for bananas for the user and returns the ID's. I am confused how this maps into the index.php file and the missing pieces.
Suggestions and links to awesome resources are most welcome. I am not interested in security or creating a state of the art Web service.
getMeMyBananas is an example of an RPC route
In REST, the four main HTTP verbs GET, POST, PUT and DELETE are the verbs to act upon a noun (a resource).
REST is not a standard. It's a loose recommendation on how to form an API for a remote system using HTTP as its foundation.
There's nothing to say that you can't design RPC-like routes in a REST API. People do it all of the time. It's just that you mainly use the verbs to create (POST), retrieve (GET), update (PUT) or delete (DELETE). That makes the acronym CRUD. So, with REST, you are able to cover a lot of scenarios in information exchange simply by sticking to CRUD.
So, you can start by designing your URLs (routes) to resemble nouns (resources) and build a switch case in PHP to switch on the HTTP verb. Keep in mind, there's nothing stopping from and there's nothing wrong with having RPC-like routes. In fact, you can't handle all cases with the simple REST CRUD scenario, so you'll have to handle cases that don't fit into that scenario with RPC-like routes.
See:
http://dojotoolkit.org/reference-guide/1.8/quickstart/rest.html
Later, if you are interested in a built out API in PHP, I built an API infrastructure and open sourced it. I'm not sure if it'll help you, but here it is:
https://github.com/homer6/blank_altumo
You can map any url to any path you want! For example, when using Apache you can use ModRewrite to turn http://ex.com/rest/bananas into http://ex.com/index.php?p1=rest&p2=bananas
From there you can now you can fetch your request parameters with the global variable get for example: $_GET["p1"].
I would suggest you to perform isset() test on those.
After that when you've got the data, I'd suggest to package it in JSON so almost any client can read it.
That's basically how I'd do it! If you've got more questions go ahead :)
I am planning to write an API using PHP and and I am very interested in HTTP protocol type of API that exists but I don't know what people call that type of API. I think you can point me towards the best guide if I let you know how I want the developers to use it.
Assuming there are following functions.
Login
SignUp
GetRequests
Now the Login should take 2 parameters Username and Password of the user that exist in the database. It should then return a token which will be used to request other resources like "GetRequests" function. So once the user has the token, s/he can call "GetRequests" passing the token and will get the information.
The SignUp function works the same way as login but the input parameters are different. It also returns a token and can be used to make other requests for resources.
There are many other functions but I believe these are enough to get an idea of what type of API I am talking about. Can you please guide me as which Tools or Frameworks I can use to develop this sort of API quickly and easily.
You don't need any specific tools or frameworks to write such a thing or to put it another way, you can use any framework you want. A typical web API "function" works just like an ordinary web page, the only difference is that is doesn't accept cookies (and other browser-specific http headers) and usually returns its output as xml or json rather than html.
What you are describing is a general implementation pattern, and isn't specific to any single approach of implementing web services.
Nowadays, many web service API's are implemented either using REST or SOAP. You would be able to implement what you are describing with either of these.
You can get a technical overview through the above Wikipedia links, or, simply google REST vs. SOAP, and you'll get lots of pages giving you the good and the bad of both approaches.
My advice would be to Learn REST, JSON. I think this tutorial Working with RESTful Services in CodeIgniter might be interesting to study.
maybe something like this ?
$command = $_REQUEST['command'];
$param = $_REQUEST['param'];
echo api::$command($param);
class api{
static function saySomething($param){
return $param;
}
}
and try access the page with
http://localhost/test.php?command=SaySomething¶m=what