Best way to implement an external API in Laravel 5? - php

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

Related

External api tranlations: Models vs call endpoint, laravel

I have a question about the best way to handle a requirement in laravel specifically.
I have two projects:
1 - One in laravel which does certain things for a company daily matters.
2 - The other one in nodejs, is just an api for translations.
How do i load this translations into the laravel project.
PLAN A AND B.
Plan A: Through models, specifying the $connection variable (that points to another sql connection) in the model.An then using the models to query by the key of the translation.
Plan B: Ussing Guzzle to make a rest call to the express node api for getting all the translations for that language. And then storing it in an array and get them from there.
Note that if i do it calling to the api. I might have to call that endpoint in each service that wants to translate something.Im also getting all the translations and i might need just a couple of keys to translate.
Thank you , i hope it was clear, and im sure this question hasnt been asked before in such a concrete manner.

Passing an array of values into Rest API Route

I am using Slim framework to create an REST API for my project. The WebApp itself is developed using ReactJS.
I have a doubt regarding the same. I have a set of values stored in an array in my ReactJS App. These values are filters which is used ti filter data from my table.
My table contains a field called location. In my WebApp I have search filter were I can add multiple locations based on which the results have to be displayed. I store these filters in an array.
I want to know how can I pass this array to Rest API Route so that I can get this array in my REST API Framework.
I want to achieve something like
/routes/location/[arrayOfValues]
There are only two ways of passing data to the server - either as URL params (for POST, GET, or anything else) or in the request body (for PUT or POST). Are you also writing the code to handle the API request? From your description of the use case, it sounds like GET would be the most semantically correct verb, so you you should use URL params as #BrianPutt suggested. Using square brackets is the standard way to encode an array value. How are the locations defined? Longitude/latitude? If so, you could also just build a comma-separated string, e.g.
/routes/location?q=12.3409,-40.0004,2.34004,120.0294
But odds are your back end framework has built-in support for parsing those URL params, so you should just use that.
/routes/location?q[]=12.3409,-40.0004&q[]=2.34004,120.0294
The only reason not to do this is if you have a huge number of locations, in which case you might want to use a POST request and build some kind of JSON object to put in the body.
Also: be consistent! If the rest of your API uses JSON, you should probably use it here too.

Fill models with Web Services

Having a basic example of a REST endpoint which returns a User json object, how would we fill our Model having that we get the data from a Web Service instead of a DB?
My approach is to have a very very basic 'SDK' with independent Classes with my data representation and access data methods, and in every method I make a call to the API with Guzzle to actually perform the action.
The problem is that I'm losing all the power that Eloquent provides.
Is there any recommended approach to do this in Laravel? Non Laravel approachs will do too.
I'd recommend to use a combination of cache and collections.
First you'll collect the web service results to a collection that you will then cache.
Something like this :
$users = Cache::remember('users', $minutes, function() use ($guzzle) {
$apiUsers = $guzzle->get('api/users'); // Get the API response as json
return collect(json_decode($apiUsers));
});
Using collections you'll have access to almost all of the Eloquent features (because it returns Collection as well. So you might do things like $user = $users->where('email', 'you#email.com')->first();
Then if you want to make it more like an "SDK", you can create a package that has classes and methods that makes it easier to get and use your API.
The problem is that I'm losing all the power that Eloquent provides.
That's not the only problem here. Your approach will be quite ineffective if you are planing to call remote API on each page display and the overall performance will greatly suffer from such approach. What you can do instead is to have your API data cached in local DB, so your models can use Eloquent to get them from with all the benefits.

How to structure a website built upon own API in laravel

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

How to call the Lithium Forum API from Zend_Rest_Client

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

Categories