I'm a new user at REST architecture, now I'm trying to make a test with my API.
I like to call this method in the url but I don't know the right format.
My concern is that I have two parameters to be sent by post request.
public function CreateExemple ($name, $libelle)
{
}
This is always be a good practice to use a ready to use package if available. There are lots of RESTful APIs available to use. It looks like you are using PHP for development. you can start with :
Zend REST
Related
I'm currently working on a project that requires me to call an external API via HTTP to get some data in the form of JSON. This data will be saved to a database pattern defined with the Eloquent ORM. This API requires authentication (by token) and then accepts calls with GET, POST is not needed. The parameters are added to the URL (e.g. ?origin=LHR&destination=GHA).
I'm trying to find a Laravel way to access such data easily - just writing a basic class that has a function with all parameters doesn't seem right. I'd much rather have some sort of query builder, but for the URL. I looked at repositories, but that seems to be geared towards database calls.
To sum up: is there any good "Laravel way" to call an external API?
I've dene something like this just few days ago;
My solution was to define array GET params. F.a.
get-some-stuff?where[foo]=bar&with[relation]&with[otherRelation]
Then you can get the params via Input::get() and go through them with an foreach.
F.a.
foreach(Input::get() as $method => $value) { ...
In the foreach you could decide what to do based on $method
I'm building a small TV Show library in laravel. I want to include an API as well for possible future expansion. When I started I had 2 controllers for what should have been a single controller: API controller and the web frontend controller. They both handled the same logic. That's obviously not good practice since that leads to duplicate code.
How would I make my application API centric? I was thinking of having an API controller which handles all the logic and returns a JSON object and a regular controller for the frontend which simply takes the JSON object returned by the API controller and passes it to a view (after, if any, processing). If that's the way to go, how would I retrieve said object? A GET request to my own server?
If you are developing API, than it should be on a separate server to take off load form main web server.
If it is on a same server, why would you send a request to it as you can develop a class that can act as API and call it inside your web controllers.
Later on when you decide to have separate server, just wrap API contoller around that class.
<?php
$myApi = new MyApi();
$myApi->setParmas( $paramsArray );
$myApi->doLogic();
echo $myApi->asJson();
// or make API class that can handle one liner
echo MyApi::factory($_GET)->doLogic()->toJson();
?>
Make your Laravel application an API endpoint and use a frontend framework or some frontend routing and templating libraries to handle the client-side.
Name space the api with /api and versions i.e. /api/v1
This allows you to easily develop with many different technologies and not have to rewrite your backend, as it is just an API endpoint.
It can then serve your webapp, an iOS app, an Android app, etc. because all it does is handle data, validation, requests, security, etc.
You can use repositories to get required data, then you may pass it to a View to make a webpage, or just print the JSON, for the API, this way you can prevent duplicate code.
Route::get('/latest', function () {
return View::make('latest', Movie::latest());
}
Route::get('/api/latest', function () {
return json_encode(Movie::latest());
}
Check this video for more info about repositories in Laravel: http://vimeo.com/53029232
In larval 5.3 you may want to consider using larval passport which provides a really nice way to consume your own api's from the front end without needing to worry too much about the authentication https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript
There is also a nice video on this on laracasts https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/13
I am planning to use a architecture (MVC = PHP->Yii) where I will be using REST API based architecture for native site (main web app) and non-native (apps such as iPhone, BB, WAP etc).
No my question is it advisable to use View-Controller (HTML+User Requests) (For Main Site) with Controller-Model (Request/Response+DB) (for API) and same API platform will be used for non-native apps, or should I use full MVC for main site and build separate platform for APIs. This is because I don't want additional HTTP (cURL) overhead for main site.
Update:
#karmakaze
That's the though with me but still I have to write RestControllers because there is lots of code involved. So anyway we ends up having two different controllers e.g.
UserController extends CController {
actionRegister() {
...Some calculations
.
.
Instead of making Calls to model We will use call controller i.e.
$userRest = new UserRestController();
/*
* This will return json data or php obj depending on params passed or
* may raise an exception
*/
$userRest->actionCreate($param1, $param2);
// Process data obtained.
}
}
or is there any other way around?
If it fits your needs, you may build a front-end based on some JavaScript libraries like AngularJs, BackBone.JS or any other MVC JavaScript library.
This way you should build only one RESTful API in Yii, as the back-end of your app.
This solution, however, lets something uncovered: it will be hard to make the application crawlable.
The perspective of the question made me to understand that it is relatively important to render the HTML on the server side. I am thinking at this solution:
make normal MVC app, including controllers and views
Use any of the following ticks:
a GET parameter that will be false by default, but ture when it is an API call:
Check this example:
// in a controller:
public function actionView($id, $api=false) {
// some calculations, getting the $model variable
if ($api) {
echo $model->json_output(); // you can implement it in components/model.php or generate the json output some other way
} else {
render('view', array('model'=>$model));
}
}
a subdomain called, for instance, api (you'll have api.yourapp.tld),
or use another HTTP parameter from the request to determine if it is an API call or not.
Any of these version will bring a way of verifying if the client requests a JSON/XML response (API call) or HTML for the browser.
This way you avoid the headache of building separate controllers for the API and the main site.
Note It is not required to do this trick for actions when they simply render a form - it is useless.
Note 2 You can use the latter method to render the requests with _request_fragment and assume that every request is an API call unless $_GET['_request_fragment'] is specified. Like this you can make an AngularJs, Blackbone.js app crawlable with Yii.
UPDATE The _request_fragment is specified here, and it is used by most search engines to crawl AJAX web applications.
You can use the same for both native and non-native app, it will also reduce you work at development time as well update or change ur logic.... I do have so many experience with such situation..
Use full MVC for main web app and reuse the same Models and Controllers to build the REST API. There are extensions which will do this automagically if you follow Yii conventions while building the main web app. Just search REST in the Yii extensions. We'll be doing the same for our mobile apps. Currently investigating RESTFullYii.
I'm trying to access a Lithium Forum Rest API using Zend_Rest_Client. The API is described here:
http://cl.ly/3N0M2D0k0H3L0Y103Q3R
The API docs give example calls such as e.g. /boards/id/experimentations/messages/id/938
How can I replicate this call Using Zend Rest Client and specifying each individual method / parameter?
I can get a response by putting the entire URL in my new Zend_rest_Client($url) call but I want to have more than control so that I can pass dynamic board and category ids.
I have tried something like
$result = $client->arg('categories')->arg2('id')->arg3($cat->string_id)->arg4('boards')->arg5('nested')->get();
and also
$result = $client->categories($cat->string_id)...
But the parameters are ignored. Can anyone shed any light on this?
If anyone wanted to try it, there is a live API here:
http://lithosphere.lithium.com/lithium/restapi/vc/boards/nested
looks like this particular API is not compatible with Zend_Rest_Client as it doesn't seem to support methods and parameters in the URI as the client expects. The solution is to build dynamic URLS to call via GET or use POST parameters
Over the last few weeks I've been learning about iOS development, which has naturally led me into the world of APIs. Now, searching around on the Internet, I've come to the conclusion that using the REST architecture is very much recommended, due to its supposed simplicity and ease of implementation.
However, I'm really struggling with the implementation side of REST. I understand the concept; using HTTP methods as verbs to describe the action of a request and responding with suitable response codes, and so on. It's just, I don't understand how to code it.
I don't get how I map a URI to an object. I understand that a GET request for domain.com/api/user/address?user_id=999 would return the address of user 999 - but I don't understand where or how that mapping from /user/address to some method that queries a database has taken place.
Is this all coded in one PHP script? Would I just have a method that grabs the URI like so:
$array = explode("/", ltrim(rtrim($_SERVER['REQUEST_URI'], "/"), "/"))
And then cycle through that array, first I would have a request for a "user", so the PHP script would direct my request to the user object and then invoke the address method. Is that what actually happens?
The main thing I'm not getting is how that URI /user/address?id=999 somehow is broken down and executed - does it actually resolve to code?
class user(id) {
address() {
//get user address
}
}
Actually the API you're trying to describe now is not RESTful. There are many sources describing how to make RESTful APIs. So you should first define your API (taking in account how your client software would use it) and then implement it. I'm quite sure that almost any RESTful API can be implemented in PHP.
Here are some other tips on how to make a RESTful API.
In my opinion GlassFish Server REST Interface is a good example of RESTful design.
That's two questions.
To honor RESTful HTTP verbs, you have to query $_SERVER["REQUEST_METHOD"]. It will contain the usual GET or POST unless a more specialized HTTP request was received. The whole REST buzz is somewhat misleading in itself, and also in misusing the HTTP verbs just for routing.
Anyway, the mapping of request URLs to functions can be achieved in two ways. It's most reliable to use a static map, for example an array that lists URL patterns and destination methods. Most PHP frameworks use an implicit mapping like so:
$args = explode("/", trim($_SERVER['REQUEST_URI'], "/"));
$class = array_shift($args);
$method = array_shift($args);
call_user_func_array("$class::$method", $args);
Note how this is a bad example, security-wise. Only allowed and specifically prepared classes and methods should be able to receive requests. Most frameworks just check if it was derived from an acceptable base class after loading it from a known path and/or instantiating. But a static map is really preferable.
Anyway, regular expression mapping or handling by mod_rewrite is also common. And for utilizing HTTP verbs, just include it as method name.
Have a look at FRAPI - http://getfrapi.com/
As it says focus on your business logic, not presentation.