I am currently learning about REST applications, and particularly Java implementations of REST.
I am unsure of what role JSON or XML plays in in REST?
An example to show my current understanding:
User clicks a button on front end.
User is re-directed to a URL e.g /user/{userid}
Java method in service class calls repository (e.g. Crud Repository) class to retrieve data
Repository pulls data from db (e.g. about that specific user)
data passed back to service class and is then shown on the UI to user.
Where does JSON or XML fit into this process?
If we divide your 5th step...
1) data is returned from service in a certain format
2) UI receives it in that format and display it on the screen.
This format is XML or JSON or even plain text. This is the Accept type you mention when making a call from UI, and set the response header in service.
JSON stands for Javascript Object notation, hence if the response is in JSON format, you can directly use it as a javascript variable by just parsing it using JSON.parse. The Accept type is actually depends on your requirement. For most of the cases JSON is preferred, as it is easily converted to JS object.
It is the format that the data is returned from the service to the front end.
The transmission of data between the front end and the api is done in JSON and/or XML.
So, simplisticly...
the user asks for some data, through some web page, and the web page asks the RESTful API for the specific data, the api sends the web page the data as JSON, then the web page manipulates that and displays it or does whatever it needs to do with that data.
That is a general way to describe its role
A Method inside the controller is shown below which give json response
#RequestMapping(value = "/getSomething", method = RequestMethod.POST)
public #ResponseBody String getSomething(HttpServletRequest req)
{
JSONArray jsonArr = new JSONArray();
Collection someList = new ArrayList();
someList = someService.getsomeList(req); // here you get the response from service class to controller
Iterator iter = categoryList.iterator();
while (iter.hasNext()) // iterate the colleection
{
JSONObject jsonObj = new JSONObject();
SomeClass someObj = (SomeClass) iter.next();
jsonObj.put("name", someObj.getName());
jsonArr.put(jsonObj);
}
return jsonArr.toString(); // return jsonstring as response
}
This is how it can be processed in view (Say JSP). Here an ajax call made to controller and response set to the field in the page.
$.ajax({
url : "getSomething.htm", //request send to controller
type : "POST",
data : {
'someData' : data
},
success : function(data) {
var arr = JSON.parse(data);
response($.map(arr, function(item) {
return {
value : item.name, //setting the value to the view
};
}));
}
});
Hope this helps!
As other have said, in your example JSON/XML fits at the end of the chain (almost), when data is returned from the server to the client.
Think of JSON and XML (and other formats) as a type of box. Some boxes are made of plastic, some are made of cardboard since they serve different purposes.
JSON/XML are types of "boxes" for the data you are sending/requesting to/from the server.
In your example:
User clicks a button on front end.
User is re-directed to a URL e.g /user/{userid}
Java method in service class calls repository (e.g. Crud Repository) class to retrieve data
Repository pulls data from db (e.g. about that specific user)
Data from DB is "translated" from the server's data format ("type of box") into a more common format (like JSON or XML)
Data in JSON/XML format is sent to the front-end for displaying purposes
Think of it this way: if there wasn't a common format for people/systems to refer to, then if you query an Oracle database you would need to be able to understand that format. If you then had to query a Sybase database, then you would need to be able to understand that as well.
To solve this, you can pick a "common" format (a box that it's easier to fit in more trucks, as opposed to a box that can only be transported by a specific type of truck) and thus make it easier to "transport" that data around.
So in essence, JSON/XML is just a way of representing data, and as such it can be used to represent data that was originally in other "hard to read" format and make it easier to read or work with.
For example by returning your DB objects as JSON you can display them in a web page because most web page frameworks understand JSON as opposed to very few of them natively understanding Oracle/Sybase formats (there are drivers to do this but it is beyond the scope of this toy example).
You can also use it to communicate with other servers that also understand JSON (like third-party APIs for example) and thus if servers A and B have different data representations (internally one is Oracle backed and the other is Sybase backed) they can still talk to each other using a "common" format like JSON.
Related
I have a input field or you can assume its a question, for which the user interaction can be of 3 types.
Text
Selection (multichoice)
Image upload (multiple medias)
I want to understand what should be the standard way to accept these responses.
I was thinking to have an API and request like below for Selection
http://example.com/input/{id}/response
Request Sample
{
"selections": [id1, id2]
}
for text type
http://example.com/input/{id}/response
Request Sample
{
"inputValue": "some input provided"
}
for media type
http://example.com/input/{id}/response
Request Sample
{
"files": [
{"name":"medianame", "type":"mediaType"}
]
}
But then if user wants to add a new file to the existing response, there need to be another API
http://example.com/input/{id}/response/{responseId}/upload
This doesn't seem right and readable, what could be the possible best design solution ?
I am currently taking a course in app development and I am trying to use Facebooks API for GET requests on certain events. My goal is the get a JSON file containing all comments made on a certain event.
However some events return only a an "id" key with an id number such as this:
{
"id": "116445769058883"
}
That happends with this event:
https://www.facebook.com/events/116445769058883/
However other events such as (https://www.facebook.com/events/1964003870536124/) : returns only the latest comment for some reason.
I am experementing with facebook explore API:
https://developers.facebook.com/tools/explorer/
This is the following GET requests that I have been using in the explorer:
GET -> /v.10/facebook-id/?fields=comments
Any ideas? It's really tricky to understand the response since both events have the privacy set to OPEN.
Starting from v2.4 of the API, the API is now declarative which means you'll need to specify what fields you want the API to return.
For example, if you want first name and second name of the user, then you make a GET request to /me?fields=first_name,last_name else you will only get back the default fields which are id and name.
If you want to see what fields are available for a given endpoint, use metadata field. e.g. GET /me?metadata=true
I'm trying to use Olingo to provide a client for interacting with an OData service (also written in Olingo). I'm trying to send a PATCH. However, the standard validation routines are kicking in and if I do not include those elements of the entity that are marked as non-nullable using the standard Olingo tools, I get an error.
in https://olingo.apache.org/doc/odata2/tutorials/OlingoV2BasicClientSample.html it says:
With an HTTP MERGE/PATCH it is also possible to send only the to be updated data as POST Body and omitting the unchanged data. But this is (currently) not shown within this sample.
Unfortunately I'm not sure how to do this, there, doesn't seem to be anywhere to flag to the EntityProvider.writeEntry method that it is a PATCH not a POST/PUT
EntityProviderWriteProperties properties = EntityProviderWriteProperties
.serviceRoot(rootUri).omitJsonWrapper(true).contentOnly(true)
.build();
// serialize data into ODataResponse object
ODataResponse response = EntityProvider.writeEntry(contentType,
entitySet, data, properties);
At this point in my code I get an error if "data" does not contain an entry for my non-nullable fields. The response also returns null values for all the attributes of the entity that aren't in my "data".
I deal with this by manipulating the response to remove all entries not in my "data" after the "standard" generation, but imagine that there must be a better way, even if I can't see it. Any suggestions on how to deal with this?
You have to create an "ExpandSelectTreeNode" which contains only the name of the selected properties to be serialized.
Assuming that your data is a HashMap with the values you can use following code as an example to start from:
// data = new HashMap<>();
ExpandSelectTreeNode node = ExpandSelectTreeNode.entitySet(entitySet)
.selectedProperties(new ArrayList<String>(data.keySet())).build();
EntityProviderWriteProperties properties = EntityProviderWriteProperties
.serviceRoot(rootUri).omitJsonWrapper(true).contentOnly(true)
.expandSelectTree(node)
.build();
// serialize data into ODataResponse object
ODataResponse response = EntityProvider.writeEntry(contentType,
entitySet, data, properties);
Best Regards
Is the contenttype from the client application/json-patch+json ?
I'm trying to implement a basic web application from the values that we are getting from web-service, it will include two datatables, each of them need to be populated in server-side.
For example, web-service have a structure like this ( Let's say these are books)
Firstly i am getting the string GUID value for the objects that i want to get an information, after that i am sending a request with the parameter of this GUIDs to service to get information XML for these book objects that includes name, page and author of them.
But as an important information, my servlet needs to get these values dynamically as soon as the page of datatable is changed, if this datatable will include 30 book ( i will get the 30 guid firstly so i can clarify that ) after that, send one request for 10 of them to show them on first page of datatable, if user clicked on page two, server behind needs to send request for the other group of ten and returns me result to show on the table.
I tried to implement the structure below :
http://www.codeproject.com/Articles/359750/jQuery-DataTables-in-Java-Web-Applications#ServerSideProcessing
but it populates a table with the DataRepository ones with all of them, so with this point of view i can't use it dynamically as i totally requested.
The main need for this, XML return for many objects needs so long time.
So do you know any example link or tutorial such a need for this ?
Thank you for informations in advance!
#Hayra, thanks for providing the Code Project link to the JQuery-DataTable example, it is very helpful. This is something that I might implement soon.
What I understood from the example, the JQuery-DataTable keeps track for you specific parameters that will allow you to return the exact number of records. The specific parameters that you need are "iDisplayStart" and the iDisplayLength". The "iDisplayLength" is set when the user specifies 10 records per page and the iDisplayStart, will is set when the page number changes.
So look at the code in the Code Project example doGet Method, this section of the code returns only the subset of records back to your table.
JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
if(companies.size()< param.iDisplayStart + param.iDisplayLength) {
companies = companies.subList(param.iDisplayStart, companies.size());
} else {
companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength);
}
try {
JsonObject jsonResponse = new JsonObject();
jsonResponse.addProperty("sEcho", sEcho);
jsonResponse.addProperty("iTotalRecords", iTotalRecords);
jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
for(Company c : companies){
JsonArray row = new JsonArray();
row.add(new JsonPrimitive(c.getName()));
row.add(new JsonPrimitive(c.getAddress()));
row.add(new JsonPrimitive(c.getTown()));
data.add(row);
}
jsonResponse.add("aaData", data);
response.setContentType("application/Json");
response.getWriter().print(jsonResponse.toString());
} catch (JsonIOException e) {
e.printStackTrace();
response.setContentType("text/html");
response.getWriter().print(e.getMessage());
}
I hope this help
I'm trying programmatically retrieve list of all design documents in the given bucket via CouchbaseClient. I have followed creating-views-from-sdk documentation but its only explains how to create view. What I need it a way to retrieve all design documents and their views. Any solution out there?
So far I was able to get only one design document...but the name is not coming from the server, e.g.
CouchbaseClient client = new CouchbaseClient(urls, bucketName, bucketPassword);
DesignDocument dc = client.getDesignDocument("MY-HARDCODED-DOC-NAME");
List<View> views = (List<View>) dc.getViews();
for (View view : views)
{
// process view data
}
What I'm trying to accomplish is to write an utility to import/export views from a given couchbase bucket. Since, strangely enough this basic function can't be found anywhere in the admin tools that come with couchbase.
I don't think you can do this with the java client, but there is an endpoint you can hit with an HTTP client from java to get this info:
http://localhost:8091/pools/default/buckets/mybucketname/ddocs
Just replace mybucketname with the bucket you want to get ddocs for. You will need to supply the basic auth header to hit this endpoint so be sure to not forget that part. You will get back json that you can then parse to get the names of the ddocs in the bucket.