RESTful Api or direct access? - php

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.

Related

difference between rest api and normal json_encode response

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.

connect to php API from php website

I'm quite new to PHP. As a learning project, I'm currently building a website on which users can order products.
I don't want my website to connect to the database I have directly, but I want that process to go through an API I've made. The API has a quite simple structure: the index.php receives the call and the variables (through post) and then, depending on the type of data received, runs one of the functions in one of it's controllers.
So, the question:
How do I set up a connection between my website and my php api (on the same server) to access my database?
I have searched the web and SO for API connections but most of the questions are about the FB API and oAuth etcetera. If I have missed a similar question please inform me because then I'll delete this question.
Any help would be much appreciated, Thank you in advance!
Sounds like you want to implement a REST API. There are a boatload of tutorials and helpful links that you can find very easily to read up on this subject. (Here is a decent starting point). There are also many, many frameworks that you can use that handle RESTful interactions automatically.
EDIT:
Once you have a REST API setup, the best way to connect and interact with your API in PHP is using the cURL module. This is a good intro to the subject of using cURL in PHP.
The current preferred structure for passing data from API -> client is JSON. PHP makes it trivial to work with JSON. Within your API use json_encode to convert a PHP variable into it's JSON equivalent string. Inside your client, convert the JSON response from your API into a PHP object using the inverse function: json_decode
This is a very well known/widely used technique and there are many more nuances to consider, but this should be a sufficient intro for testing purposes. Once you understand the ideas I strongly recommend doing some google/stackoverflow searches and reading more on the subject.

RESTful API in PHP for a script outputting in JSON format

I am a PHP programmer and new to RESTful services. I have developed a page which outputs the data in JSON format, based on query parameters (_GET). Now I wan't to implement it so that I can call my script with different parameters via REST API.
My question is, how would I go about implementing the API in PHP. Basically, I am developing this so we can integrate the same data that is there on our website in a different interface for our client sites.
I already have most of data exposed in JSON format, just need guidance on how to implement the RESTful service for that.
are you comfortable with php frameworks? than you should give a shot to laravel php framework its is really awesome with low learning curve.
You can use json_decode of php and you will get array. You can use decoded array values for further processing. You can make a http post request or curl alternatively to make a rest request.
Or you could use Slim if you don't like Laravel for some reason. Take a look at https://github.com/victorjonsson/PHP-Rocker it will get you up an running in minutes

Designing a basic Restful API in PHP

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

PHP API Development

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&param=what

Categories