codeigniter: Rest api + Json - json

How, do I implement code igniter rest API that outputs with ajax outputting the JSON. I'm unsure how to use the REST API for deleting and adding with the JSON. How to delete a item from the JSON and then from the database.

1. Rest API routing
Let's start with the routing of your API - If you apply best practice to your API you will want to use HTTP verbs (POST/PUT/GET...). (Read more on HTTP Verbs and REST here)
If you are on Codeigniter 2.x then read this SO question and answer
If you are on Codeigniter 3.x then read this documentation
On the other side, if you are planning to use the API only internally and the scope of the project is limited you can just ignore HTTP verbs and simply make POST and GET calls to your controllers.
2. Creating JSON response
Generally you will not need to use views - you can have your controllers echo the JSON response. Here is an example of a fictional API that has an API call to get an actor from a database of actors.
/* ----------------------------------------------
| Example of an API Method to get an actor from
| a database of actors:
| call: http://example.com/api/GetActorById
| parameter: actor_id
| Method: POST
*/
public function GetActorById(){
// Let's first get the actor ID from the POST data
$actor_id = $this->input->post('actor_id');
// If the API Method would be GET you would get the
// actor ID over the URI - The API call would look
// like this: http://example.com/api/GetActorById/<actor_id>
// In that case you take your actor ID from the segment:
$actor_id = $this->uri->segment(3);
// Do your database query magic here!
// ...
// ...
// Let's create an array with some data
// In real life this usually comes from a DB query above
$data = array(
'Firstname' => 'Michael',
'Lastname' => 'Fox',
'IsActor' => True,
'UserId' => 1234567
);
// Now let's convert the array into a JSON
$json = json_encode($data);
// if the API is accessed from a different domain
// you will want to allow cross domain access
header('Access-Control-Allow-Origin: *');
// Now let's return the json
echo $json;
}
The output will look like this:
{"Firstname":"Michael","Lastname":"Fox","IsActor":true,"ActorID":123456789}
Hope this helps - Good luck with your project!

Related

How do I display json get result using Wix Code?

I'm working with a non-profit cat shelter trying to update their website. They want to have a page that connects to their shelter manager software to display the available cats for adoption. Luckily, their shelter manager offers API calls to get the information I need from it.
They use Wix as their platform and are pretty set on keeping it as most of their volunteers know how to make easy adjustments to other pages. I researched and found Wix offers the ability to connect to the API using their fetch method.
Basically, I am trying to get a dynamic page to display a repeater that is populated from their json API Get method.
Currently, for the backend I have (URL to API removed for security):
import {fetch} from 'wix-fetch';
export function getdata(){
return fetch('URL to API Service', {method: 'get'})
.then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
} );
}
On the page, this is where I think I am getting stuck:
import {getdata} from 'backend/fetchCats';
getdata()
.then(json => {
console.log(json);
var catData = json;
// static repeater data
$w.onReady(function () {
// handle creation of new repeated items
$w("#repeater1").onItemReady( ($item, itemData, index) => {
$item("#text23").text = itemData.ANIMALNAME;
} );
// set the repeater data, triggering the creation of new items
$w("#repeater1").data = catData;
} );
});
The above is giving me the error: Wix code SDK error: Each item in the items array must have a member named _id which contains a unique value identifying the item.
I know the JSON call has an ID field in it, but I am guessing Wix is expecting an _id field.
Am I just doing this wrong? Or am I missing something simple? I've spent a couple nights searching but can't really find a full example online that uses Wix's fetch method to get data via my HTTPS Get.
Thanks for any help!
You are doing fine.
You are getting the error from the line $w("#repeater1").data = catData;
which is the line used to set the items into the repeater. A repeater expects to have a _id member for each of the items, and your data quite probably does not have such an attribute.
I assume the API you are using, when returning an array, each item has some identifying attribute? if so, you can just do a simple transform like -
let catDataWithId = catData.map(item => {
item._id = item.<whatever id attribute>;
return item;
});
$w("#repeater1").data = catData;

Response cache for Symfony REST API

I have a REST API using the FOSREST Bundle. The response is serialized by the JMS Bundle. Now I want to cache some of the responses because serialization takes quite some time. I was thinking of storing the response data after serialization and then, if database hasn't changed, deliver the cached response instead of doing serialization again. Any ideas how to achieve this?
To be more specific:
I have a Controller which outputs a lot of data which is unchanged most of the time. Since serialization takes a few seconds I want to speed up things
using the cached output.
I think I need to setup an event "afterSerialization" to write the cache.
But because fosrestBundle is configured to serialize all data handled by the view, I don't find a method to output pre serialized data without beeing sent to the serializer again.
public function postProductsAction(Request $request)
{
$em = $this->get('doctrine')->getManager();
// TODO check if db is unchanged and cache exists
// if check is true stop here and redirect to cached json response
$products = $em->getRepository('PPApiBundle:Produkte')->findBy(array("status" => 1));
$data = array(
"data" => $products,
"opt" => array()
);
$view = $this->view($data, 200);
$ret = $this->handleView($view);
// TODO cache json string after serialization
return $ret
}
You can use query cache and response cache methods of doctrine query builder to cache results before serialiation.
->getQuery()->useQueryCache(true)->useResultCache(true, 3600)

Send a queryset of models from Django to React using Ajax

I've been looking for info about this for hours without any result. I am rendering a page using React, and I would like it to display a list of Django models. I am trying to use ajax to fetch the list of models but without any success.
I am not sure I understand the concept behind JSon, because when I use the following code in my view:
data = list(my_query_set.values_list('categories', 'content'))
return JsonResponse(json.dumps(data, cls=DjangoJSONEncoder), safe=False)
It seems to only return a string that I cannot map (React says that map is not a function when I call it on the returned object). I thought map was meant to go through a JSon object and that json.dumps was suppose to create one...
Returned JSon "object" (which I believe to just be a string):
For the time being I have only one test model with no category and the content "At least one note "
[[null, "At least one note "]]
React code:
$.ajax({
type:"POST",
url: "",
data: data,
success: function (xhr, ajaxOptions, thrownError) {
var mapped = xhr.map(function(note){
return(
<p>
{note.categories}
{note.content}
</p>
)
})
_this.setState({notes: mapped})
},
error: function (xhr, ajaxOptions, thrownError) {
alert("failed");
}
});
Can someone please point me to the best way to send Models from Django to React, so I can use the data from this model in my front end?
I recommend using the Django REST Framework to connect Django to your React front-end. The usage pattern for DRF is:
Define serializers for your models. These define what fields are included in the JSONified objects you will send to the front-end. In your case you might specify the fields 'categories' and 'content.'
Create an API endpoint. This is the URL you will issue requests to from React to access objects/models.
From React, issue a GET request to retrieve a (possibly filtered) set of objects. You can also set up other endpoints to modify or create objects when receiving POST requests from your React front-end.
In the success function of your GET request, you will receive an Array of Objects with the fields you set in your serializer. In your example case, you would receive an Array of length 1 containing an object with fields 'categories' and 'content.' So xhr[0].content would have the value "At least one note ".
In your code, the call to json.dumps within the JsonResponse function is redundant. Check out the docs for an example of serializing a list using JsonResponse. If you are serializing the object manually (which I don't recommend), I'd use a dictionary rather than a list -- something like {'categories': <value>, 'content' : <value>}. DRF will serialize objects for you like this, so the fields are easier to access and interpret on the front-end.

Var dumping a JSON object with laravel with JSON Formatter

I'm trying to figure why I whenI browse to a page that has JSON data it won't display it in the JSON formatter with the jSON Formatter plugin installed on my local computer. Anybody know why this could be the issue? What are some possibilities for me to look into?
/**
* Display a listing of users
*
* #return Response
*/
public function index()
{
// Retrieve all users from database with roles and statuses
//$users = User::with('role')->with('status')->get();
$users = User::all();
var_dump($users);
// Return a view to display all users by passing users variable to view.
//return View::make('users.index', compact('users'));
}
I'm not familiar with the tool your post mentions, but when you say
var_dump($users);
you're not returning JSON. You're returning an HTML page that contains text contents that looks like dumped JSON.
I'm going to guess that the "jSON Formatter" plugin you mentioned looks for property JSON response headers to decide if it should handle a request or not. Try the following instead.
public function index()
{
// Retrieve all users from database with roles and statuses
//$users = User::with('role')->with('status')->get();
$users = User::all();
return Response::json($users);
}

PUT requests with Custom Ember-Data REST Adapter

I'm using Ember-Data 1.0.0.Beta-9 and Ember 1.7 to consume a REST API via DreamFactory's REST Platform. (http://www.dreamfactory.com).
I've had to extend the RESTAdapter in order to use DF and I've been able to implement GET and POST requests with no problems. I am now trying to implement model.save() (PUT) requests and am having a serious hiccup.
Calling model.save() sends the PUT request with the correct data to my API endpoint and I get a 200 OK response with a JSON response of { "id": "1" } which is what is supposed to happen. However when I try to access the updated record all of the properties are empty except for ID and the record on the server is not updated. I can take the same JSON string passed in the request, paste it into the DreamFactory Swagger API Docs and it works no problem - response is good and the record is updated on the DB.
I've created a JSBin to show all of the code at http://emberjs.jsbin.com/nagoga/1/edit
Unfortunately I can't have a live example as the servers in question are locked down to only accept requests from our company's public IP range.
DreamFactory provides a live demo of the API in question at
https://dsp-sandman1.cloud.dreamfactory.com/swagger/#!/db/replaceRecordsByIds
OK in the end I discovered that you can customize the DreamFactory response by adding a ?fields=* param to the end of the PUT request. I monkey-patched that into my updateRecord method using the following:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
And poof we haz updates!
DreamFactory has support for tacking several params onto the end of the requests to fully customize the response - at some point I will look to implement this correctly but for the time being I can move forward with my project. Yay!
EmberData is interpreting the response from the server as an empty object with an id of "1" an no other properties in it. You need to return the entire new object back from the server with the changes reflected.