REST

155

Solutions

1

Articles & Videos

314

Contributors

Representational state transfer (REST) is an architectural style that gives a coordinated set of constraints to the design of components in a distributed hypermedia system used to design networked applications. RESTful systems typically communicate over Hypertext Transfer Protocol (HTTP) with the same HTTP verbs (GET, POST, PUT, DELETE, etc.) that web browsers use to retrieve web pages and to send data to remote servers. REST interfaces with external systems using resources identified by Uniform Resource Identifier (URI) that can be operated upon using standard verbs.

Share tech news, updates, or what's on your mind.

Sign up to Post

Dear Sirs,
I have a web app rendering html and exposing at the same time some REST end points.
I have 2 two classes annotated with @ControllerAdvice:
1) A Class will manage all the errors generated on the web side of the application, and redirects to an Error view page
2) The other Class will manage all the errors generated on the REST side of the application and returns an ResponsEntity<Object>

I have some custom exceptions such as NotFoundException, AccessDeniedException, etc.. And there is a generic ExceptionHandler for the Class Exception.class in both the 2 @ControllerAdvice Classes: 1 for web side exception and 1  for REST side exception.

The confusion  I am seeing is that when the generic exception occurs, while I am consuming the REST end points, I will get an HTML error view instead of a Jackson string representing the ResponseEntity<Object> and vice-versa.

How can I handle this. Make @ControllerAdvice Class 1 only look at exceptions generated by all the classes annotated with @Controller, and @ControllerAdvice Class 2 only look at exceptions generated by all the classes annotated with @RestController.


Thanks a in advance
0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Dear sirs,

I have CSRF enabled in my REST application.
I use either RestTemplate or Postman as Client.
How can I set the application in a way that each request (POST/PUT/DELETE) is carried with a token in its header.

I remember using an implementation of  ContainerRequestFilter while working on Jersey, and I could take care of my requests globally.

I am looking forward to hearing from you.
0
I am using REST API with SharePoint 2013 and I want to know if the following url endpoint is legal or if there is a better way?
 //http://myspsite.com/nrm/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=DIR,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq '402-CSI-001'     //<---  Works when I paste it in the browser
 var projNum = '402-CSI-001';
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=DIR,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq "+projNum;  //<---  Not valid when I run it in my code

Open in new window


Error I get in my js file
rest api error
js file
function loadSPItems() {
var projNum = '402-CSI-001';
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=VISN,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq "+projNum;//,ProjectNumber,ApprovalStatus,ProjectExecutionStatus”;
var headers = { 
	"accept": "application/json;odata=verbose" 
}
 
jQuery.ajax({ 
	url: endPointUrl, 
	type: "GET", 
	headers: headers, 
success: function (data) {
	console.dir(data);
}, 
	error: function (err) { 
	alert("Error Occured:" + JSON.stringify(err)); 
}
 
});
 
}

loadSPItems();

Open in new window




Thoughts?
0
Which Database Choose?

This Article about choose the NOSQL database based on application requirement. Different NoSQL DB’s available, there are three primary concerns you must balance when choosing a data management system: consistency, availability, and partition tolerance.

 

* Consistency means that each client always has the same view of the data. * Availability means that all clients can always read and write.

* Partition tolerance means that the system works well across physical network partitions.

 

Chose the Database system based on your application requirement.

 Example Comparing MongoDB and CouchDB.

As you can see in the diagram, MongoDB and CouchDB are built with a slightly different focus. Both scale across multiple nodes easily, but MongoDB favours consistency while CouchDB favours availability.

In the MongoDB replication model, a group of database nodes host the same data set and are defined as a Replica set. One of the nodes in the set will act as primary and the others will be secondary nodes. The primary node is used for all write operations, and by default all read operations as well. This means that replica sets provide strict consistency. Replication is used to provide redundancy - to recover from hardware failure or service interruptions.

CouchDB uses a replication model called Eventual consistency. In this system, clients can write data to one node of the database without waiting for other nodes to come into agreement. The …
0
I have a user form that is created in extjs framework. The user form has many user fields which are being passed as part of request payload to the REST controller. I am trying to add a grid panel(most likely in a tabular format with multiple rows & columns) to the user form. But I am not sure how to pass the grid panel data as part of request payload to the REST controller. I will post more code if any more details are needed. Any help would be appreciated. Thanks.

Ext.define('soylentgreen.view.admin.UserForm', {
    extend : 'Ext.form.Panel',
    alias : 'widget.userform',
    bodyStyle : 'padding:5px 5px 0',

// some userform elements like firstname,lastname, go here.....

name : 'userTeamGrid',
  xtype : 'gridpanel',
id : 'userTeamGrid',
itemId : 'userTeamGrid',
multiSelect : true,
selModel : Ext.create(
        'Ext.selection.CheckboxModel',
        {
          injectCheckbox : 'first',
          mode : 'MULTI',
          checkOnly : false
        }),
anchor : '100%',
width : '700px',
height : 250,
flex : 1,
store : 'userTeamStore',

var user = form.getRecord();
form.updateRecord(user);
user.save({
        callback : function(records, operation){
          //reset the (static) proxy extraParams object
          user.getProxy().extraParams =  {
            requestType: 'standard'
          }
          if(!operation.wasSuccessful()){
            var error = operation.getError();
0
I am trying to call REST services deployed on Tomcat 8 from Angular 4. Since both these are running on separate domains, CORS issue is expected. So, in the tomcat/conf/web.xml, I have added the below filter
<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Authorization,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping> 

Open in new window


This is how I am sending the GET request from Angular
var basicOptions:RequestOptionsArgs = {
  url: 'http://server3:7000/myrest/info',
  method: RequestMethod.Get,
  search: null,
  headers: new Headers(
    {'Authorization': 'Basic AG1hZG1pbjpkZW1vLmRlbW8=' },
    ),
  body: null
};

basicOptions.headers.append('Content-Type', 'application/json');

var reqOptions = new RequestOptions(basicOptions);
var req = new Request(reqOptions);
return this.http.request( req );

Open in new window


Since, I am sending the Authorization header, it is also added in the 'cors.allowed.headers' param in Tomcat.

When I call the REST service from Chrome, it always gives me a 'Invalid CORS request' error (Network tab -> Preview). Below is the error in browser console
XMLHttpRequest cannot load http://server3:7000/myrest/info. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

Open in new window

Is there something else that I need to do to make it work?
0
I have an XML file that when passed through SOAP UI returns a proper response as XML file. I need to create an application to pass the XML and recuperate the response. I tried searching but many say REST web service where they using only post/get.

Please send me some sample code and/or tutorials.
0
I am exporting a table using pdfmake
The table exports, but there is one item that is 'undefined'.  

I have a main page with multiple tabs and once you hit the 'Printer Friendly' btn, a pdf report opens in a new tab for the specific tab you selected.  The 'printer friendly' btn is what exports the page.  

This code broadcasts  the print function to produce the pdf report depending on what tab you are on.
$scope.printDiv = function(divName) {		
		$rootScope.$broadcast('print');		
	}
	

Open in new window


and the button
<button ng-click="printDiv('rollup-tab')">Printer Friendly</button>

Open in new window



Here is the rest of the code.

Table creation and exports the pdf pdf
$scope.$on('print', function(event, filter) {
			var docDefinition = {

					content: [	
					          {
						  table: {

					              body: [                   			                
					                [ 
					                  '',
					                  'Actual Pieces Issued',
					                  {text: $filter('mcGoalNumberFilter')($scope.actualPiecesMCGoal) + ' /wk'},			                  
					                  {text: $scope.actualPiecesMon, style: 'tableData'},
					                  {text: $scope.actualPiecesTues, style: 'tableData'},
					                  {text: $scope.actualPiecesWed, style: 'tableData'},
					                  {text: $scope.actualPiecesThurs, style: 'tableData'},
					                  {text: $scope.actualPiecesFri, style: 

Open in new window

0
I have a simple REST Api app and have no issues when sending a GET request, everything works as expected. However, when I send either a PUT, POST or DELETE request, I just get 204 - No Data response and none of the code in the relevant methods is executed.

This what I have in my WebAPIConfig.vb file:

Public Module WebApiConfig
    Public Sub Register(ByVal config As HttpConfiguration)
        ' Web API configuration and services

        ' Web API routes
        config.MapHttpAttributeRoutes()

        config.Routes.MapHttpRoute(
            name:="DefaultApi",
            routeTemplate:="api/{controller}/{id}",
            defaults:=New With {.id = RouteParameter.Optional}
        )

    End Sub

End Module 

Open in new window


and the PUT method in the controller is simply logging the fact we got a request, but the code doesn't run:

' PUT: api/Barcode/5
        Public Sub PutValue(ByVal id As Integer, <FromBody()> ByVal value As String)

            auditLog("REST Call", "Received PUT request", False, False)

        End Sub

Open in new window

0
I have an on prem SharePoint 2013 site collection.  On that site, I have a form where I can add list items (records to the external SQL table).  It has been working fine and dandy.  Yesterday, the table was migrated to another SQL Server and version (2016).  Now,  I can add and modify the records on any browser other than IE (used to work there).  I get back a 400 error.

Any advice on this would be greatly appreciated.
0
Monthly Recap
Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

i want to send email notification to few external users .

Tried using designer 2013 /2010 workflow.

Also tried JSom code using Rest Api
0
Hello Guys , i need a GPO for work life balance , just locking computer automatically after 4 hrs of activity and unlock it after 10 min of rest
0
Hi All,,,

Requirement is as follows:
(It may sound crazy or stupid but I welcome any better suggestions).
- I am pulling out a set of records in a Continuous Form based on a selection Query.
- When I update a text field, I want the change to reflect in the same field in the rest of the record set.

I did an Update Query which I run in the 'After Update event'  of the field.
Two scenarios:
1- When I include a Saverecord in the update event after running the Updating Query, I get the attached Error Message.
2- If I don't Saverecord in the AfterUdate, then I get caught with the same error message upon closing the form.

In both cases, the update query does its job very well.

On the Error Message:
- If I choose 'Copy to Clip Board', 'Save Record' or 'Drop Changes', nothing happens and  I can continue to close and nothing is affected to the updated fields.

I have observed the behavior very closely and it is fine EXCEPT the annoying Error Message, which sounds scaring.

Please advise of :
- Either a way to suppress the Error Message, or
- A better suggestion to achieve the requirement.


Many Thanks

BTW:
This is not a multiuser environment not even a split DB. It is confined to my PC only as it is still under development .

Write Conflic1
0
How to parse the  JSON Data using Rest web service give me a simple example
0
Hi Experts,

I have created a google rest api call using postman and can successfully retrieve an email from my gmail account. However, I need to extract some text from the body and it is coming back encrypted such as below

 "body": {
          "size": 2717,
          "data": "PCFkb2N0eXBlIGh0bWw-DQo8aHRtbD4NCjxoZWFkPg0KPG1ldGEgY2hhcnNldD0iVVRGLTgiPg0KPHRpdGxlPkNvbXBsZXRlIHlvdXIgUmVnaXN0cmF0aW9uPC90aXRsZT4NCjwvaGVhZD4NCg0KPGJvZHkgc3R5bGU9ImZvbnQtZmFtaWx5OkdvdGhhbSwgJ0hlbHZldGljYSBOZXVlJywgSGVsdmV0aWNhLCBBcmlhbCwgc2Fucy1zZXJpZjsgbGluZS1oZWlnaHQ6MS42ZW07IGZvbnQtc2l6ZToxNHB4Ij4NCjwhLS1baWYgbXNvXT4NCgk8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCQlib2R5LCB0YWJsZSwgdGQge2ZvbnQtZmFtaWx5OkFyaWFsLCBIZWx2ZXRpY2EsIHNhbnMtc2VyaWYgIWltcG9ydGFudDsgbGluZS1oZWlnaHQ6MS42ZW07fQ0KCTwvc3R5bGU-DQo8IVtlbmRpZl0tLT4NCgk8dGFibGUgc3R5bGU9InBhZGRpbmc6MTBweDsgd2lkdGg6YXV0bzsgbWFyZ2luOjAgMTAlIj4NCiAgICAJPHRyPg0KCQkJPHRkPg0KCQkJCQk8cCBzdHlsZT0idGV4dC1hbGlnbjpjZW50ZXI7Ij4NCgkJCQkJPGltZyBzcmM9ImNp.........

Open in new window


Has anyone had experience extracting data from the body or can offer any suggestions on how I can convert the data field into someting rreadable

Thanks
0
I am working with excel 2007 and I have changed my printer settings, selected all then changed the page set up, changed in print settings while under print entire workbook. All three option print the first page in color and the rest black and white and double sided. Right now I am going tab by tab to update the page setup - is there a better way to do this though.
0
Dears,
Some servers over the network I can open normally like \\severname\c$ with no issue but the rest of the servers I can't like I don't connect to the network.
I have windows 10 and this is normal netwrok with Microsoft active directory. The other machine I can connect and do it by my users to access all servers but not from my machine anymore.
Regards
Mostafa
0
Hello all,
our HTTP packets go via a proxy, unlike the rest of the TCP/IP packets.
so using ping to measure the latency between us and a webserver won't be very accurate. we need to measure latency over HTTP instead of ICMP.
any help ?
0
websites provide android app fetching from rest api.
websites provide  rest api using c# with just one controller in project and sql server 2016 sending/receiving data for one table.
So these are not compact,efficient for complete project with multiple tables.
I am very curious to have modular code for all these concepts.
0
Stressed Out?
Stressed Out?

Watch some penguins on the livecam!

I have the below code that is returning undefined. How to rewrite so it uses a promise or similar mechanism to ensure addTSRecord returns the id to TimesheetRecords?

TimesheetRecords[i].id = addTSRecord(TimesheetRecords[i].RowID, moment(myWE).subtract(6, 'd').toISOString(), TimesheetRecords[i].TSStaffId, TimesheetRecords[i].Hours, TimesheetRecords[i].TSTaskId);						

function addTSRecord(myRow, myDate, myTSStaffID, myHours, myTSTaskID) {

		var endpointUrl = mySite + "/_api/web/lists/getbytitle('timesheets')/items";
		
		call;

		var call = $.ajax({
    		url: endpointUrl,
    		type: "POST",
    		data: JSON.stringify({
    			"__metadata": { type: "SP.Data.TimesheetsListItem" },
    			RowID: myRow,
    			TSDate: myDate,
    			TSStaffId: myTSStaffID,
			Hours: myHours,
			TSTaskId: myTSTaskID
	        }),
    		headers: {
    			Accept: "application/json;odata=verbose",
    			"Content-Type": "application/json;odata=verbose",
    			"X-RequestDigest": myFormDigest
    		}
		});

		call.done(function (data, textStatus, jqXHR) {
			return data.d.Id;
		});

		call.fail(function (jqXHR, textStatus, errorThrown) {
    		var response = JSON.parse(jqXHR.responseText);
    		var message = response ? response.error.message.value : textStatus;
    		console.log(message);
		 });
		
	}	//	addTSRecord

Open in new window

0
Why can't we write an efficient query to check if any results are not started with a set of alphabets? I am using this https://wordpress.org/plugins/alphabetic-pagination/ but i don't know that how can i check if rest of the alphabets are not having any results in it.
0
Ransomware - Wannacry/wcry and everything else ...

Ransomware in general is something none of us wish to deal with.  The latest Wannacry problem is worse.  This is not because of what it is but rather of the extent to which it has affected our users.  There have been a plethora of great suggestions all over this site.  I would add to those with the following suggestions:
•      Completely check your system for viruses with a reputable virus checker
•      Check any suspected files and or links at virustotal.com
•      Make sure you have a tested versioning backup system
•      Do a complete scan of your system
•      Updates
        o      Make sure all your programs and your operating system is up to date (even old Windows OS’s now
                have updates, like windows XP – check the Microsoft website and do a windows update)
        o      If you are unable to do updates on your own machine due to company policy, make sure that your IT
                department is doing the updates.
•      Do not, click on an attachment in your email, even if it is from someone you know – call them up and check
        that they sent it – they’ll understand.

Whenever I touch a system I do a “ransomware check” which involves the following:
•      Create a blank text file called myapp.txt in the root drive (c:\) and rename it to myapp.exe
•      Run FoolishIT’s Cryptoprevent
•      Install an anti-ransomware tool such as BD Antiransomware, MBAM Antiransomware, Kaspersky
        Antiransomware for business, etc.
•      …
20
 
LVL 95

Expert Comment

by:John Hurst
The overall advice to keep automatic updates on to keep updates current, keep Antivirus up to date and firewalls up to date is something we have said many times in here (sometimes to deaf ears).

Two really important points. Stop the excuses and dump all desktop operating system earlier than Windows 7 and all server operating systems earlier that Server 2008.

Second: get top notch spam filters. That is how this malware gets in.
3
 
LVL 13

Expert Comment

by:Natty Greg
I can not stress enough about proxy and spam filter, content filter along with gateway antivirus scanning, patching all systems and educating users.
2
I have a requirement to use one controller that accepts two posts.
I receive the following exception "Multiple actions were found that match the request"

I realize this not ideal and it would make sense to just have a second controller. However, that is not an option. How can I complete this?
0
Searching for the user ID (integer) in Zendesk... test user has actual  id=22335667888 but the command I send to search for her returns id=2.2335667888E10

What is the best way to sanely convert that back? Can I always just remove the . and the E10?
0
Hello,
My questions are not being posted?
Administrator; Why?
It appears that this question got posted, so I will actually ask a question.
I have an external monitor hooked up to my laptop.  I have the font setting on the monitor set.
When I open Ready API! 1.9.0 the fonts are very tiny and I do not find where or how to change the size.
I do not want to change the size or resolution of the monitor.
Thanks
0

REST

155

Solutions

1

Articles & Videos

314

Contributors

Representational state transfer (REST) is an architectural style that gives a coordinated set of constraints to the design of components in a distributed hypermedia system used to design networked applications. RESTful systems typically communicate over Hypertext Transfer Protocol (HTTP) with the same HTTP verbs (GET, POST, PUT, DELETE, etc.) that web browsers use to retrieve web pages and to send data to remote servers. REST interfaces with external systems using resources identified by Uniform Resource Identifier (URI) that can be operated upon using standard verbs.