I finally got my API output ready with some great help of SO-members answering all my questions. Thank you by the way.
But I wonder about one thing in my output. When I call the URL to receive the API content I get something like this:
[
{
"data": [
{
"incidentReference": "R-20150405-887f93",
"latitude": 48.259698,
"longitude": 11.434679,
"archived": false
},
(...)
]
}
]
I read the book "Build APIs you won't hate" and it is a great resource for a lot of stuff. But I don't think, the output I see is right. I mean, the namespacing is something I would like to have. But shouldn't it look like this?
{
"data": [
{
"incidentReference": "R-20150405-887f93",
"latitude": 48.259698,
"longitude": 11.434679,
"archived": false
},
(...)
]
}
So shouldn't the whole thing be JSON only? in my case it is return additionally within an Array. The functions doing the job are these:
public function index()
{
$incidents = Incident::all();
if( ! $incidents) {
return Response::json([
'error' => [
'message' => 'There are no incidents in the database.',
'code' => 100
]
], 404);
} else {
return $this->respond([
$this->respondWithCollection($incidents, new IncidentTransformer)
]);
}
}
public function respond($data, $headers = []) {
return Response::json($data, $this->getStatusCode(), $headers);
}
protected function respondWithCollection($collection, $callback) {
$resource = new Collection($collection, $callback);
$rootScope = $this->fractal->createData($resource);
return $rootScope->toArray();
}
So yes, the respondWithCollection returns an array, but this is handled within the respond function which states return Response::json So I would expect a json output when calling the resource.
Is this ok?
The next structure
{"data" : [{}, {}]}
is good when you have an extra fields, such as total count of items, number of page, etc:
{"data" : [{}, {}], "page":1, "total": 100}
Otherwise, it is really good to use simple structure:
[{"incidentReference": "R-20150405-887f93", ...}, {...}]
I'd recommend you to avoid any deep-nested structures.
RESTful responses should be as simple as possible : Output pure json data only. Therefore, limit and offset should not be included in the server response since this client already knows that information. And if you format the response, you will have to interface all device / plateform / system that wants to interact with your resful service.
Server should return extra information that client doesn't know though, such as total elements when querying a part of a collection. But I would use header for that. That way, server still returns simple json array, wich can be handled not only by your client but lots of other devices / platforms / apps.
My opinion : Output only pure json and use header for extra info, like this example :
api/incidents/index.php :
// sanitize $_GET array, then output
$total = $incidents->getTotal();
$output = json_encode($incidents->fetch($GET['LIMIT'], $_GET['OFFEST'])); // pure example, I don't know how your framework works
// output
header('HTTP/1.1 200 OK');
header('Content-Type: application/json');
header('Collection-Total: '.$total);
header('Content-Length: ' . strlen($output));
echo $output;
For example, a web app using jquery accessing this ressource would look like this :
var limit = 10;
var offset = 200;
$.ajax({
type: 'GET',
url:'http://mywebsite.com/api/incidents/',
data: {
'LIMIT': limit,
'OFFSET': offset
},
success: function(data, textStatus, request){
console.log('Incidents received...');
console.log(data);
console.log('There is ' + request.xhr.getResponseHeader('Collection-Total') + ' incidents in total');
},
});
I would avoid nested structures, like Roman said. RESTful ressources need to have their own identifier (URI). It must return an object (item) or array of objects (collection of items), like this :
api/incidents // returns an array of objects
api/incident/[id] // returns a unique object (incident), using incident id in the URI
api/incidentreference/[id] // return an unique object (incident reference), usign incident reference id in URI
This approach also leads to interesting cache possibilities since all elements (item or collections) have their own identifier (URI). Web protocols / platforms / devices may cache all server results and optimize your entire app automatically if you work with URIs.
I would also recommend that your service return a 200 OK responses even if there is no elements to output. 404 says that the ressource is not found. The ressource is found, but contains no elements now. It may contains elements later. A 404 HTTP code may be handled differently by some device / broswers / platform. I am possibily wrong with that, but my REST services always return 200 OK / empty json arrays and I never has problems. Accessing a ressource (url) that doesn't exists will return 404 though.
Related
I have a forum project with Laravel 9, and I have made this helper function.
if(!function_exists('new_question')){
function new_question($c) {
$quelist = \DB::table('questions')->get();
$quecount = $quelist->count();
if($quecount > $c){
return 'A new question is added.. please refresh the page..';
}
}
}
So it gets the number of current questions like this:
{{ new_question($queCnt); }}
And then, it will check if the $quecount equals $queCnt or not. And if not, then print the statement A new question is added.. please refresh the page... Therefore the user will understand if any new question is added. But I need to run this helper function after some periods of time (for example, 10 seconds). However, I don't know how to call a function after a custom amount of time.
to run any function after a specific time, you have set the interval for example
// Call the new_question function every 10 seconds
setInterval(new_question, 10000);
// Use an AJAX request to call the new_question function on the
// server
function new_question(){
$.ajax({
url: '{{ url('/new_question') }}?c=10',
success: function(response) {
// Handle the response from the server
console.log(response);
}
});
}
</script>
// to receive get value update helper function
if(!function_exists('new_question')){
function new_question() {
// Get the value of the c parameter from the query string
$c = isset($_GET['c']) ? $_GET['c'] : 0;
// Your code here...
}
}
First, you have to figure out if the number of "content" has changed. Using Laravel, create a function that is accessible through a route, this function would return the number of posts, then, using javascript, you will call that function in an interval (example is 5 seconds) and if the number has changed since the last call, then there's new posts, so you should do some DOM manipulation to update your page to alert the user.
Your server side function would be simple, something like this:
function count_questions() {
$quelist = DB::table('questions')->get();
$quecount = $quelist->count();
$response = array('quecount' => $quecount);
echo json_encode($response);
}
Then, identify how to reach this function through your routing table, and use the below jquery functions:
var quecount = 0;
$(document).ready(function() {
setInterval(function() {
$.ajax({
// change this URL to your path to the laravel function
url: 'questions/count',
type: 'GET',
dataType: 'json',
success: function(response) {
// if queuecount is 0, then set its initial value to quecount
if(quecount == 0){
quecount = response.quecount;
}
if(response.quecount > quecount){
quecount = response.quecount;
new_question_found();
}
}
});
}, 5000);
});
function new_question_found(){
$("#new_questions").html("New questions found");
}
The solution that is coming to my mind is may be too advance or too complex.
This solution need
Laravel scheduler and queue (Jobs)
and web push notification (ex : one-signal)
To reduce the traffic in the back-end you can have job to run like every 10 seconds in the back-end (Laravel scheduler and Queue).
If the question count get increased. you can call a api in the push notification and you can say there is a new question added.
the above work-flow is not explained well but this is in very simple term.
For example:
on frontend side:
const check_new_questions = function() {
const message =
fetch('http://yourserver.com/new_questions_endpoint');
if (message) {
// show message
}
};
// call each 10 seconds.
setInterval(check_new_questions, 10000);
then on backend side:
create a route new_questions_endpoint which will call your function and return result as response.
But note, that receiving all the questions from the table each time could be expensive. Eloquent enables to make a count query without retrieving all the rows.
You can't have this behaviour happen without any form of javascript.
The main way you could do this is by setting an interval via front-end like others have said. If you have any familiarity with APIs and general HTTP protocol, I would recommend you make an API route that calls your helper function; I also recommend responding with an empty body, and using the http status code to determine whether a refresh is needed: 200 for success and no refresh, 205 for success and refresh needed.
So you simply set a fetch api call on timeout, don't even need to decode the body and just use the response status to determine whether you need to run location.reload().
To achieve your requirement as per the comment you need to create an ajax request to BE from FE to check the latest question and based on that response you need to do it.
setInterval(function()
{
$.ajax({
url: "{{url('/')}}/check/questions",
type: "POST",
dataType: "json",
data: {"action": "loadlatest", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
}, 10000);//time in milliseconds
the above js code will create an ajax request to Backend, below code will get the latest question 'id'.
$latest_id = DB::table('Questions')->select('id')->order_by('created_at', 'desc')->first();
so either check it in BE and return a corresponding response to FE or return the latest id to FE and check it there.
then show the prompt to refresh or show a toast and refresh after 5 sec
Why do you use function_exists() ? I don't think it's useful in this case.
The easiest way to do what you want is to use ajax and setInterval
Front side:
const check_new_questions = function() {
const data =
fetch('http://yourserver.com/new_questions_endpoint?c=current');
if (data) {
alert(your_message);
}
};
// call each 10 seconds.
setInterval(check_new_questions, 10000);
Back side:
function new_question() {
// Get the value of the c parameter from the query string
$c = isset($_GET['c']) ? $_GET['c'] : 0;
$quelist = \DB::table('questions')->get();
$quecount = $quelist->count();
return ($quecount > $c);
}
I suggest to use c as the last id and to not count questions but just to get the last question id. If they are different, one question or more was inserted.
Attention if you use this solution ( Ajax pulling ) you'll get two requests per 10 seconds per connected users. One for the ajax call and one for for the database call. If you have 10 users a day, it's ok but not if you have 10 thousands. A better but more complex approach is to use Mercure protocol or similar ( https://mercure.rocks/ ).
I followed this tutorial to set up my back end server based on Yii framework and then this tutorial to set up my API and everything is working as it should.
But I am not sure how to accomplish the next step:
My return array right now is pulling records that look like this:
{
"id": 1,
"user_id": 1,
"description": "This is a summary of article 1",
"status": 2,
"type": 1,
"created_at": 1426210780,
"updated_at": 1426365319
}
The value for 'type' is '1' in the db, but I want to store all the possible values of 'type' in another table like this:
1 : Red
2 : Blue
3 : Green
And then I want the JSON returned via my API to contain "type":'red' instead of "type":1. I assume I need to override something in my Model, but I can't figure out what to override or with what.
I'm happy to read through tutorials or documentation but I'm such a beginner at this that I'm not sure what terms to search for. Thanks for your help!
Have a look at models and their relationships to other models, this will allow you to get the information you need.
http://www.yiiframework.com/doc/guide/1.1/en/database.arr
Once the relationship is working correctly you should be able to get the colour from the original model.
Although this is from a earlier version of Yii it may help you understand how the models will interact as well
http://www.yiiframework.com/wiki/285/accessing-data-in-a-join-table-with-the-related-models/
#Burrito's response provided documentation but I want to give the full solution for other searchers:
First, I needed to set up a model for 'Type'.
Second, I needed to declare the relationship between 'Report' (my main model) and 'Type' like this (in my Report model):
public function getType()
{
return $this->hasOne(Type::className(), ['id' => 'type']);
}
(I'm not sure if that step is necessary, but the documentation makes it seem necessary.)
Third, I created getTypeName (in Report model), to get the name of the type based on the ID:
public function getTypeName($type = null)
{
return Type::findOne($type)->name;
}
Lastly, in my apiController, I modified the function that I am using to get all records to include a loop for each record that called getTypeName:
protected function findAllReports()
{
// get all reports
$reports = Report::find()
->asArray()
->all();
if( $reports ){
$i = 0;
// loop through each report
foreach($reports as $report){
$model = new Report();
// add a new key/value pair to each report array, populate with getTypeName and pass the type ID to it as a parameter
$reports[$i]['typeName'] = $model->getTypeName($reports[$i]['type']);
$i++;
}
return $reports;
} else {
// error or no results
}
}
For reference, the other routine needed here is the action that the API hits, which calls findAllReports():
public function actionList()
{
$reports=$this->findAllReports();
$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>$reports),JSON_PRETTY_PRINT);
}
Finally, now if I called [url]/api/list, I get an array of reports, including the typeName.
I have a Backbone App with Codeingiter as Backend. I use the RESTful API setup to pass data back and forth between these to Frameworks.
Now I want to have a View which shows me the "newest followers", for that I created an API like this:
public function new_artist_followers_get($start_date, $end_date)
{
$this->load->database();
$sql = "SELECT users.img_name FROM artist_followers INNER JOIN artists ON artists.artist_id = artist_followers.artist_id INNER JOIN users ON users.user_id = artist_followers.user_id
WHERE artist_followers.artist_id = artists.artist_id AND date_time BETWEEN '$start_date' AND '$end_date' LIMIT 20";
$query = $this->db->query($sql);
$data = $query->result();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any artist followers!'), 404);
}
}
My issue is that I'm not really sure how to pass the dates to my Backbone frontend? Do I have to do it somehow like this?:
NewFollowers.NewFollowersCollection = Backbone.Collection.extend({
url: function() {
return '/projects/testproject/index.php/api/testfile/new_artist_followers/'+ this.artist_id + this.startdate + this.enddate;
}
});
Normally, I fetch an API exactly like in the example above, just without the this.startdate and this.enddate and then in my MainView i gather everything, where I for each API/Collection do this (in this case an artist biography):
beforeRender: function() {
var artistbioCollection = new Artistbio.ArtistbioCollection();
artistbioCollection.artist_id = this.artist_id;
this.insertView('.artistBio', new Artistbio.View({collection: artistbioCollection}));
artistbioCollection.fetch();
....etc. etc. ...
}
So can anyone help me out?
Backbone.Collection fetch method accepts extra parameters, they should be passed like this:
artistbioCollection.fetch({
data: {
start_date: this.startdate,
end_date: this.enddate
}
});
It is in Backbone documentation
So here, data is the same property as jQuery.ajax data property, you can then grab these values server-side as usual.
As fetch perfoms a GET request, all parameters passed to data will be appended to query string
You should use URI templates to define the URI on the server side, like so:
http://example.com/api{/artist,id}/followers{?stardate,enddate}
After that you can use for example this library to fill this template on the client side with params. You can add a custom setter for those params, for example (not tested):
NewFollowers.NewFollowersCollection = Backbone.Collection.extend({
url: function() {
return URI.expand("http://example.com/api{/artist,artistId}/followers{?startDate,endDate}", this.params).href();
},
setParams: function (artist, start, end){
this.params = {
artistId: artist.get("id"),
startDate: start,
endDate: end
};
}
});
Be aware, that this is not a complete REST solution. By REST you get hypermedia responses, which contain links. One of those links can contain the actual URI template and a parameter description. So your client is completely decoupled from the URI structure, it does not know how to build an URI, but it knows how to evaluate an URI template, which is a standard solution. You decouple the client from the implementation of the service using standard solutions, this is called the uniform interface constraint of REST.
I'm trying to get geolocation from tweets.
For my tests, I posted new tweets geo-referenced but when I got the json of them, the element 'geo' is null. Why? What's wrong with them?
I don't want to search by range and geolocation: I want to search some tweets indexed by a particular hashtag and then retrieve 'geo' json element.
I tried to search other tweets (not mine) and sometimes I got 'geo' element as a full object, with coordinates array.
So, what can I do to have 'geo' element not null?
I did 4 posts geo-referenced: my tweets
The location is: 44.694704,10.528611
Edit: Added geocode param
This is what I've done server-side (pure php):
$conn = new OAuth (CONSUMER_KEY, CONSUMER_SECRET);
$conn->setToken (ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$conn->fetch (API_URL, array ('q' => '#testhashtagandgeo', 'geocode' => '44.694704,10.528611,4km'));
echo $conn->getLastResponse ();
I used PHP OAuth base and each constant is defined correctly, so it works good.
Client-side (ExtJS):
Ext.onReady (function () {
Ext.Ajax.request ({
url: 'proxy.php' ,
disableCaching: false ,
success: function (xhr) {
var js = Ext.JSON.decode (xhr.responseText);
Ext.each (js.results, function (tweet) {
if (tweet.geo !== null) {
console.log ('lat = ' + tweet.geo.coordinates[0] + ' - lng = ' + tweet.geo.coordinates[1]);
}
});
console.log (js);
} ,
failure: function (xhr) {
console.log ('something\'s wrong!');
}
});
});
Thanks in advance.
Wilk
You need to read the documentation
Location data is only included if the query includes the geocode parameter, and the user Tweeted with Geo information.
So, you need to add something like this to your query
&geocode=37.781157,-122.398720,25mi
Or whichever location you want.
Here is what I have so far:
var Item = Backbone.Model.extend({
defaults: {
id: 0,
pid: 0,
t: null,
c: null
},
idAttribute: 'RootNode_', // what should this be ???
url: 'page.php'
});
var ItemList = Backbone.Collection.extend({
model: Item,
url: 'page.php',
parse: function(data) {
alert(JSON.stringify(data)); // returns a list of json objects, but does nothing with them ???
}
});
var ItemView = Backbone.View.extend({
initialize: function() {
this.list = new ItemList();
this.list.bind('all', this.render, this);
this.list.fetch();
},
render: function() {
// access this.list ???
}
});
var view = new ItemView();
Current (expected) json response:
{
"RootElem_0":{"Id":1,"Pid":1,"T":"Test","C":"Blue"},
"RootElem_1":{"Id":2,"Pid":1,"T":"Test","C":"Red"},
"RootElem_2":{"Id":3,"Pid":1,"T":"Test2","C":"Money"}
}
This successfully polls page.php and the backend acts on $_SERVER['REQUEST_METHOD'] and returns the required information, however I don't know why the collection is not filled.
In the parse function of ItemList it properly shows me all the output, but it does nothing with it.
I left some comments in the code for some more precise questions, but the main question is why doesn't the collection populate with the obviously received data?
Modify your parse method to:
parse: function(response){
var parsed = [];
for(var key in response){
parsed.push(response[key]);
}
return parsed;
}
To follow conventions, change list inside ItemView to model. Also in render():
render: function() {
var template = _.template("<div>some template</div>");
this.model.each(function(item){
this.$el.append(template(item.toJSON()));
}, this);
return this;
}
The parse method you're supposed to be returning the data after doing whatever necessary parsing is required for it.
The common use case for parse would be if you're sending back an object of a form like:
{ "id" : "NaN", "tasks": [ *all your models in a list here *] }
then you'd use parse like so:
parse: function (data) {
return data.tasks
}
Backbone then handles the rest.
Is there a particular reason why you're sending the data back in that dictionary format? It's not exactly clear how you intend to map that to each model of the collection. Is the key irrelevant? if so, you should be passing back a list of the objects in the values.(Although see note at bottom). If not, and you want to attach it to the models, it should be moved to the object you're using as a value and send back a list.
* Note: Don't actually send back a JSON list bare. There is an exploit for GET requests that relies on lists being valid javascript on their own, where a malicious site can use the Array object and override it to use a script tag to your API to use the users credentials to pull down whatever information is available in that call. Instead, when wanting to send back a list you should use something like this:
{ result: [*list here*] }
Then you just use the parse method above to extract the list.