What is the difference between jsonrequest and httprequest? - json

I was checking the files in the controllers of web module in both OpenERP-7.0 and OpenERP-6.1. Then I found that 6.1 uses jsonrequest (#openerpweb.jsonrequest) 7.0 uses httprequest (#openerpweb.httprequest). What is the difference between the two ?

I didn't look at OpenERP v7 but OpenERP v6.1 uses both - HttpRequest and JsonRequest. I suppose it's the same for OpenERP v7...
Both of them are about communication between client and server. HttpRequest communicates trough the well known GET and POST methods. That means the following:
The client send a request encoded in the url (GET method) or in the http body (POST method)
The server returns an object corresponding to the request. Could be an html page, PNG image, CSS file, JavaScript, XML encoded data or whatever.
JsonRequest is an implementation of another protocol for client/server communication - JSON-RPC 2.0. You may want lo look here for more information. It's a remote procedure call (RPC) protocol which means that it allows the client to initiate the execution of some method on the server passing some arguments to this method. In response the client gets some data as a result of the method invocation.
EDIT - some more words about the decorators #openerpweb.jsonrequest and #openerpweb.httprequest
Some methods are decorated with the #openerpweb.jsonrequest decorator, other methods - with the #openerpweb.httprequest. This means nothing else but that the first group of methods will be available for execution trough the JSON RPC protocol and the second group will be accessible trough the pure HTTP protocol.
Now, what is the difference? And do we need both jsonrequest and httprequest? Let simplify it like this: JSON is more suitable for executing methods on the server and obtain results. HTTP is simpler and easier to use when all we what is to access some resource on the server.
Let's 'decorate' this with some examples for clarity. Take a look at the following method of the web.controllers.main.Export class:
#openerpweb.jsonrequest
def formats(self, req):
""" Returns all valid export formats
:returns: for each export format, a pair of identifier and printable name
:rtype: [(str, str)]
"""
...
This method accepts some arguments and returns a list (Python list object) containing all known export formats. It will be called in a programmatic way in some python code on the client side.
On the other side are the 'http' methods - like the method css() of the web.controllers.main.Web class:
#openerpweb.httprequest
def css(self, req, mods=None):
....
All this method does is to return a CSS file to the client. It's a simple action like accessing an image, a HTML web page or whatever other resource on the server. The resource we are returning here is nothing complicated as a Python list as in the previous example. We don't need a special format to encode it additionally. So we don't need additional data encoding format as JSON and remote procedure call protocol as JSON RPC.

Related

What is the difference between Protocol and Json Wire Protocol

Protocol: A standard to define a method of exchanging data over a network.
If a browser wants to communicate with a server, it has to create an HTTP request and send that HTTP request to the server to convey its request of resources and options. The server receives the request and process it and do the needful and create an HTTP response to send to the browser. The browser has to follow the HTTP specification in creating the HTTP request. The server also has to follow the HTTP specification in creating the HTTP response. This is how the communication between the browser and the server happens in a standard way to avoid conflicts by following the HTTP protocol.
Json Wire Protocol: A client has an object that has to be sent to a server. The client converts this object into a JSON object and sends it to the server. The server parses the JSON object and converts it back to object for use. The server converts the response object into a JSON object and sends it back to the client. The client then converts the JSON object to object for use.
Why the later is called as Json Wire Protocol?
You are pretty correct both about Protocol and JsonWireProtocol. At this point it is worth to mention that, earlier all implementations of WebDriver that communicated with the browser, or a RemoteWebDriver server shall use a common wire protocol. This wire protocol defines a RESTful web service using JSON over HTTP.
JSON Wire Protocol is an abstract specification of how automation behavior like clicking or typing or whatever you actually want to do with your automation script is mapped to selenium or appium or HTTP requests and response. The protocol will assume that the WebDriver API has been "flattened", but there is an expectation that client implementations will take a more Object-Oriented approach, as demonstrated in the existing Java API. The wire protocol is implemented in request/response pairs of "commands" and "responses".
What is JSON Wire protocol?
JSON (JavaScript Object Notation) is a lightweight format for data exchange between client and server. Applications use JSON objects to send and receive data between each other in the web world. JSON data structure is industry standard and can be used for sending and receiving data as Key & Value pair. Some people say its a very nice alternative for XML. We can save JSON files as .json extension.
How JSON looks like?
A simple json file looks like below and there are many online editors which can be used to edit and verify JSON structure.
{
"Student":{
"FirstName":"Pawan",
"LastName":"Garia",
"IdNumber":"12345",
"City" : "New Delhi",
"EmailID" : "email#gmail.com" }
}
Why JSON Wire Protocol was used in first place?
To implement a client-server architecture which can give us the following benefits.
You write test in any programming language.
You can perform or run test on cloud services like SauceLabs, BrowserStack or Selenium Grid setup.
You are not bound to run test only on the local machine.
Different Drivers(FirefoxDriver, ChromeDriver) can be crated for browsers and separate implementation by using the same standards.
So client-server implementation requires a standard set of the specification beforehand so that Server and Client should be in sync with each other in term of what is coming and going on request and response. It’s something like a language of communication with each other. So we need some common specification to solve this kind of requirement and the solution was HTTP.
Why HTTP is the solution?
HTTP is a standard for web and can be a good base for the specification. Every programming language has a good HTTP libraries which can be used for creating client and server for request and response calls.
How JSON Wire protocol worked with HTTP?
HTTP request and response are generally made of GET and POST requests which is out of scope for this discussion.
Current status
From Selenium perspective, JSON Wire Protocol is obsolete now and the WebDriver W3C Living Document is the new implementation.
WebDriver Communication
The WebDriver protocol is organised into commands. Each HTTP request with a method and template defined in the specification represents a single command and hence each command produces a single HTTP response. In response to a command, the remote end will run a series of actions known as remote end steps. These provide the sequences of actions that a remote end takes when it receives a particular command.
Command Processing
The remote end is an HTTP server reading requests from the client and writing responses typically over a TCP socket. In the specification the communication is modeled as the data transmission between a particular local end and remote end with a connection to which the remote end may write bytes and read bytes. The exact details of how this connection works and how it is established is a bigger topic and out of scope for this question. After a connection has been established, the remote end must read bytes from the connection until a complete HTTP request can be constructed from the data. If it is not possible to construct a complete HTTP request, the remote end must either close the connection, return an HTTP response with status code 500, or return an error with error code unknown error.
Outro
Difference between JsonWireProtocol mechanisms and the new standards in W3C Living Document when using Selenium

Spring Boot to return JSON String from an external API

I have a simple Spring boot project that uses controller mappings to get hard coded information from a class in my project.
For example, if I run the request : localhost:8080/topics, A JSON response is returned with the list of Topic Objects that i have previously created
I want to take this one step further and have a class who's variables are populated by calling this API and parsing the response : https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo
I believe this can be done in Java by creating a HTTP connection and reading the data from an input stream, but is the an easier way of doing this with spring boot? Im not fully sure of the name of this procedure hence Im having trouble finding solutions online
Since you are using Spring Boot, making use of Spring's RestTemplate makes sense. It comes with several message converters out of the box, and uses Jackson by default for json content.
Spring has published a good Getting Started page for consuming RESTful web services.
However, the json content returned by that services doesn't look like it will map well to a Java object, so you may have to deserialize it to a HashMap to get to the data you want.
I did an attempt to create something like this.
https://github.com/StanislavLapitsky/SpringSOAProxy
The idea is to register controller interfaces. Each of the interfaces are mapped to some URL. For the interfaces a dynamic proxy are generated (if the implementations are not available locally). So developer just call controller's interface method. The method is invoked for dynamically generated proxy. The proxy uses RestTemplate to call remote URL. It sends and receive JSON and deserializes the returned JSOn to POJO objects returned from the controller.
You need to declare contract - controller interfaces plus DTO to exchange data as well as mapping to understand which URL should be called for each controller.

Is it necessary to pass request data as JSON string to server

When making an AJAX request to a server (may be Java, PHP, etc), is it necessary to pass data as JSON string ?
Can we not pass the object directly ? Are there issues de-serializing OR can that be handled at the backend ? Any examples of handling JS object (if it is possible to send an obj directly) at the backend would be great ?
Object literal makes sense only in the JavaScript runtime environment. Since AJAX body is simply a string, you can pass {a:3} to a server. But what should server side do with it? It ertainly can store it in a database and return to you back when requested. But what if it wanted to extract some data from it? You' have to have JS runtime and evaluate the object using eval. Which would be awkward, but possible. However, not all servers have JS runtime environment. Whereas there are libraries for many languages that support parsing JSON into the representation specific to the language on the server.
An AJAX request passes data to the server in the same way any other HTTP request does. Most commonly, AJAX requests use POST and pass data to the server as POST data, but query strings are often used, and there are other ways to pass data to a server using HTTP and AJAX.
In essence all HTTP data is octets (bytes), and HTTP has no special support for serialization of JavaScript objects, so you or the libraries and/or frameworks you use must handle the serialization.

Spring RESTful service returning JSON from another service

I have been creating Spring RESTful services for a while and typically I am building my own services so I create domain objects and populate them and the framework takes care of the conversion to JSON.
I have a situation now where I simply need my service to act as a pass through to another system's service that is already RESTful and returns JSON.
URL https://:/service/serviceInfo
Method GET
HTTP Content Type Produces: application/json
I simply want to wrap this call (I will apply some security checks on the service) and pass that JSON returned straight back to my service without mapping it back to Java objects, only to return as JSON to the client. Is there a simple way to do this, with minimal code?
Thanks in advance.
Can you see if this works for you?
#RequestMapping("/child")
public String testMethod(#RequestParam String param) {
return new RestTemplate().exchange("https://api.twitter.com/1/statuses/user_timeline.json", HttpMethod.GET, null, String.class).getBody();
}
You just replace the url for your own. I can also guide you to using the RestTemplate with POST or DELETE requests etc. if you need. Also adding parameters or headers if you need. I've used it extensively in some projects.

why use http.route() method use type="json" in openerp

above code from the website_mail module controller file email_designer.py file
class WebsiteEmailDesigner(http.Controller):
#http.route('/website_mail/email_designer/<model("email.template"):template>/', type='http', auth="user", website=True, multilang=True)
def index(self, template, **kw):
values = {
'template': template,
}
return request.website.render("website_mail.designer_index", values)
#http.route(['/website_mail/snippets'], type='json', auth="user", website=True)
def snippets(self):
return request.website._render('website_mail.email_designer_snippets')
which situation we are using type="json" and type="http" and why..??
Basically type="json" is used to pass data from controller where as type="html" is for responding over http request.
For example from your above code:
the url "/website_mail/email_designer//" will respond towards any particular http request and route to its web page where as the url "/website_mail/snippets" will just pass json data to its rendered template but there is no physical webpage related to this url.
Methods that received JSON can be defined by passing 'json' to the type argument of http.route(). The OpenERP Javascript client can contact these methods using the JSON-RPC protocol. JSON methods must return JSON. Like the HTTP methods they receive arguments as named parameters (except these arguments are JSON-RPC parameters).
#http.route('/division', type="json")
def division(self, i, j):
return i / j # returns a number
Both of them are about communication between client and server. HttpRequest communicates trough the well known GET and POST methods. That means the following:
The client send a request encoded in the url (GET method) or in the http body (POST method)
The server returns an object corresponding to the request. Could be an html page, PNG image, CSS file, JavaScript, XML encoded data or whatever.
JsonRequest is an implementation of another protocol for client/server communication - JSON-RPC 2.0. You may want lo took here form more information. It's a remote procedure call (RPC) protocol which means that it allows the client to initiate the execution of some method on the server passing some arguments to this method. In response the client gets some data as a result of the method invocation.
EDIT - some more words about the decorators #openerpweb.jsonrequest and #openerpweb.httprequest
Some methods are decorated with the #openerpweb.jsonrequest decorator, other methods - with the #openerpweb.httprequest. This means nothing else but that the first group of methods will be available for execution trough the JSON RPC protocol and the second group will be accessible trough the pure HTTP protocol.
Now, what is the difference? I do we need both jsonrequest and httprequest? Let simplify it like this: JSON is more suitable for executing methods on the server and obtain results. HTTP is simpler and easier to use when all we what is to access some resource on the server.
Let's 'decorate' this with some examples for clarity. Take a look at the following method of the web.controllers.main.Export class:
#openerpweb.jsonrequest
def formats(self, req):
""" Returns all valid export formats
:returns: for each export format, a pair of identifier and printable name
:rtype: [(str, str)]
"""
...
This method accepts some arguments and returns a list (Python list object) containing all known export formats. It will be called in a programmatic way in some python code on the client side.
On the other side are the 'http' methods - like the method css() of the web.controllers.main.Web class:
#openerpweb.httprequest
def css(self, req, mods=None):
....
All this method does is to return a CSS file to the client. It's a simple action like accessing an image, a HTML web page or whatever other resource on the server. The resource we are returning here is nothing complicated as a Python list as in the previous example. We don't need a special format to encode it additionally. So we don't need additional data encoding format as JSON and remote procedure call protocol as JSON RPC.
type="json":
it will call JSONRPC as an argument to http.route() so here , there will be only JSON data be able to pass via JSONRPC, It will only accept json data object as argument.
type="http":
As compred to JSON, http will pass http request arguments to http.route() not json data.
Examples
#http.route('demo_html', type="http") // Work Pefrect when I call this URL
def some_html(self):
return "<h1>This is a test</h1>"
#http.route('demo_json', type="json") // Not working when I call this URL
def some_json(self):
return {"sample_dictionary": "This is a sample JSON dictionary"}