How to get Error message from REST service and show it at proper form field in java EE? - rest

I made a Dynamic web project using Eclipse IDE. I made a simple web app for learning.
I also made a REST service (jersey implementation) which i am using for insert,update,delete and for listing records from mysql database.
Now i want that i've a registration form which has some fields. I want that before inserting the data into database using my REST service, the service should validate form data.
I searched a lot google. I understand how to validate data in my service. But i am not getting that how to show the error message to individual form field to client.
Is there any complete example of this which does not use maven and show me the whole working from submitting form to show the error messages.
Thanks in advance..please help me guys..

You should change your approach slightly to solve this problem and implement it in the following way:
First of all You should add validation mechanisms on the client side and send registration request only when this validation will be successful.
You will find form validation tutorial for AngularJS here:
https://docs.angularjs.org/guide/forms
http://www.ng-newsletter.com/posts/validations.html
and for jQuery here:
http://runnable.com/UZJ24Io3XEw2AABU/how-to-validate-forms-in-jquery-for-validation
Server should respond with propper HTTP statuses (with optional message). For example:
200 OK (or 201 Created) - when registration finished successfully;
400 Bad Request - when registration cannot be finished successfully;
So in Your actual use case:
User fills HTML form inputs;
Inserted data are validated on the client side;
When data are invalid, error message is shown in the propper place (individual form field);
When data are correct request is sent to the serwer;
Server application tries to insert supplied data to database;
If operation is finished properly, server will answer with 200 (or 201) status code. Registration is finished.
If operation is not finished properly, server will answer with 400. Client (AngularJS, jQuery, JS) will show error message.
Hopefully, my answer will help You. Ask if You need more explanation.

Related

How to convert soap message in Oracle OSB

I'm just starting with Oracle Service Bus 12C.
I created a proxy service that takes in a couple of parameters. A pipeline that moves those parameters to the request-headers. A business service that calls my PHP. So far, the PHP receives the parameters correctly.
Next, I am returning a response from PHP. As a first step, I did a simple echo "Hello, World";
Two things are happening at this point.
Firstly, when debugging the app, JDeveloper shows that $body in Response Action is blank. However, in a log action, I added $body. That shows:
<soapenv:Body xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">Hello, World</soapenv:Body>
No idea why JDeveloper doesn't want to show this.
So, how do I get the string part from this so I can use a Insert Action to build the XML response that the proxy service would understand?
I tried these in the log action, but all of them give blank outputs:
$body/*
$body/soap-env:body
$body/soap-env:Body
$body/soap-env:Body/#value
$body/soap-env:body/#value
Edit: According to https://docs.oracle.com/cd/E13171_01/alsb/docs25/consolehelp/context.html $body/* should extract the payload without the soap-env:Body wrapper.
Got it:
$body/text()
I noticed that the tag is soap-env in the request and soapenv in the response. The $body/* works for the request to remove the wrapper in the request only.

400 Response code on post to hubspot form

I am using a plugin on a WordPress website which is supposed to feed gravity forms submissions into hubspot however, on submission I get the following error:
PHP Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: POST https://forms.hubspot.com/uploads/form/v2/XXXXXX/97d44f1e-XXXX-XXXX-XXXX-e4c453843854 resulted in a 404 Not Found response:
I've nullified the URL.
I've searched this error and read through many, many GitHub threads but no seem of any use to me - they're all about other people's bespoke implementations. Can anybody here shed any light on this for me? Is there any more information I can post to allow anybody to help me investigate deeper?
Some temp fixes I've seen circulate:
1) On your Hubspot forms, make sure they are using Thank You messages and NOT the redirect to page feature (neither are actually functional if you are using only this plugin making API requests and not using for form embed code etc provided by HubSpot)
2) Save / update your forms in HubSpot
Since doing the above (there was a mixture of the two in our case, we have not caught any further errors for the past couple days) Jury is still out on what is the true issue behind this.
Details:
I hit this issue as well. Guzzle is throwing the error after seeing the HS response. This Guzzle client was not used in the older version of the plugin, so thinking that either the request was different in previous versions (prior to v3) or HubSpot was throwing a 404 response before and it was being ignored. Data (in my testing) is still posting correctly to the HubSpot API and shown/updated in the Contact record database. But website users end up seeing a 500 error due to this issue. (As a result the analytics scripts on the thank you page never get fired so we caught this seeing a drop in GA) I'm assuming the plugin could be coded around this to ignore the exception, but still no idea why it is being provided as a response in the first place.

Check if Sailjs backend is getting a legit req from the frontend without any authentication system

I do not want my users to authenticate. But I do not anyone to steal my data. So my goal is to only serve the people who make a req from the front end of the app. How can I do this ?
Is there a built in function that I'm missing ? I know that there are session id generated, but not sure how to incorporate the session id to this situation.
Thanks
By using the term "front end" I would assume that you have a client requesting data in the form of JSON/XML or HTML templates. My first suggestion to get your answer is to be much more descriptive in your question. It is very hard to answer without knowing how your client is designed.
Assuming your client is written in html/js and run in a browser then I would suggest that you serve a static file (in the form of a .js file or a <script></script> tag inside an html file) that generates a token. You can pass this token back to your server for validation on every request for data. This means that only your app (front-end) can be the only thing that requests data from your api (back-end).

Using SoapUI to test Login function of REST application

I don't make this very general question post lightly, but I've maxed out what I can figure out on my own.
I'm starting up the QA Test Automation at my new company (they don't automate anything currently) and they've elected to use SoapUI for this procedure.
The application they're developing is a REST application (I don't really have any idea what that means) so I'm trying to build a REST request and Test Suite to reach our internal test server (which gets me XML that I am not allowed to post here - but it does reach the server successfully!) and then try to do a Login/Logout test.
I'm asking for help with methodology, because I have no idea where to start. I;ve Googled and trolled their support forums and looked in every corner of YouTube. Everyone is doing something different enough that I can't relate or use it.
Does anybody out there use SoapUI and test functional login in a REST application? I can write HTML/CSS and I'm pretty Java savvy, so I can do technical stuff if I know what to look for and what to learn.
Feeling overwhelmed. This was not in my job description when I started.
You should start with REST, and after that with SoapUI.
It is hard to catch the essence of REST.
It is like the hybrid of SOAP and a simple HTML driven web application. By SOAP you describe your web service with a WSDL. By a web application you send back hypermedia, so you don't have to write a WSDL or any descriptor to your application. This is convention over configuration...
REST uses the same approach, so it sends back hypermedia as well, but it sends not HTML, because it is not machine processable. The hypermedia sent by a REST API is usually an XML or a JSON derivative, for example ATOM+XML, JSON-LD, etc... If your web service does not send back hyperlinks, then it is not a real REST service just a SOAP web service with some REST constraints. There is a big difference. By SOAP you have to know everything about the operation name and the parameters if you want to send a request. If something changes, then your SOAP client breaks immediately. By REST your automated client follows links, checks their link-relation, or the bound linked data and recognizes which link is what it was looking for. So the modification of the link's url is irrelevant in the client, because it follows the vocabulary of the application, for example: hydra is a project which tries to describe these application level semantics in a general way, and tries to bind it to open linked data.
So at first you have to check that you have a real REST API, which follows the HATEOAS principle, or just a REST like SOAP web service. This is very important if you want to write end to end tests against it. By testing REST, you have to follow the links in your tests returned by the web API. By testing REST like SOAP, you have to build the links yourself in your tests... How to build such a link? I am sure you got a description of your REST API, but a link looks usually something like this in a JSON format:
{
rel: "link-relations",
method: "METHOD",
href: "domain/api-root/version/resource-path?map-reduce",
data: {...},
title: "...",
...
}
Ofc. there is some difference by every hypermedia, so you have to check your XML hypermedia type, how it represents links... The link-relations and maybe other attributes bind your data to the semantics of your REST API. The METHOD is always a verb, usually: GET, POST, PUT, PATCH, DELETE, maybe OPTIONS, and so on... There are only a few REST verbs, each of them has a specific meaning. In the url: The domain is the domain name of your application, e.g. https://example.com. The api-root is the root of your REST API, usually /api. The version is the version number of the currently used API, usually /v1. Only non backward compatible vocabulary changes should affect this version number. The resource-path is the path of your resource, usually /users or /users/inf3rno, etc... By REST you have resources. Each of them has a unique resource-path, and as you can see, every word in that path is a noun. So resources are something you can modify or display with a verb. For example a GET /users/inf3rno should return a representation of my profile page, and a PATCH /users/inf3rno {nick: "Leslie"} will turn my nick name: inf3rno into Leslie. By REST every resource should have only a single resource-path, so this is always a unique identifier, therefore the previous example with PATCH was not so perfect if you want to have multiple users with the same nick... The map-reduce in the queryString of the url, and it contains the sorting, pagination and filtering settings of the resource you want to modify or display. For example you can retrieve some data of every user with a first name: "Leslie" with GET /users?filters="firstName: 'Leslie'"&page=3&count=25. There is a difference between the following url-s: /users?id="inf3rno" and /users/inf3rno. The first one points to a collection resource and filters the result by its representation, the second one points to a single item resource. So a GET should return a collection representation with a single item by the first one, and an item representation by the seconds one. By the resource modifying methods there is no difference between the 2 urls... So it is recommended to add only a unique identifier to the resource-path if you want to select an item resource from a collection. By reducing the collection representation in any other ways, you have to add the filters to the queryString. The data part contains the params from the input fields. The title is the title of the link, and so on... You can use url-templates of you want to put input params to the url as well...
By REST the client maintains the session, and it sends the credentials (username, password) with every request. This is because the REST service is like John Snow, it does not know anything about the session or the identity of the user. It has to authenticate every request. To do that it uses a credentials -> permissions cache. This is a good approach, because the service scales very well if it does not have to maintain the session, which is part of the application state (the state of the client)... The REST service maintains only the resource state, which is not dependent on the clients...
The response to your REST requests is usually a hypermedia which contains the links you can follow and the data you requested. By REST like SOAP web services you get only the data in a JSON or XML format. Every response should contain a proper status header. The most frequent status codes are:
200 - ok (by successful PUT, PATCH and GET)
201 - created (by successful POST)
202 - accepted (by async request with eventual consistency)
204 - no content (by successful DELETE)
206 - partial content (by pagination with range headers)
301 - moved permanently (by migration)
304 - not modified (by cache)
400 - bad request (by invalid input)
401 - unauthorized (if no password given, or wrong username or password)
403 - access denied (if your account does not have permission to perform the task)
404 - not found (by unknown resource)
409 - conflict (by concurrency issues or duplicated request or db constraint problems)
410 - gone (if the resource was present before, but it is already deleted)
415 - unsupported media type (if the client wants the response in an unknown media type)
500 - internal server error (if the request was okay, but something went wrong by processing it)
By any error you have to send a detailed error message with a custom error code, which is understandable for the users, not just the developers...
That's how a REST API looks like.
To test it with e2e tests you have to set fixtures send REST requests and check their response. So it is like any other test... The SoapUI is not necessarily the best tool to do that, I read many complaints about it... I personally never used it, but it is not so hard to write your custom testing system. You need a testing framework, which can compare expected and actual values. You need something to send HTTP requests, or simply mock out the HTTP framework of the REST API. You need something for the fixture. By integration tests you can mock out the business logic and the HTTP framework as well, so by those you just inject the mock dependencies and check the calls. By e2e tests you need a test data set, and compare it with the result XML in your case... If you want to e2e test your client, you can use selenium if it is HTML based, maybe with nightwatch.js. By testing a real REST API, you'll need an automated browser, like selenium for your REST API implementation, which can select and follow the proper links. If you are developing the REST API you would write a browser like that anyways if you want an example client for your 3rd party client developers.

Asp.NET Web Api: Returning meaningful errors to client?

I have created myself a standard asp.net web api project and it has a Post on there.
The post basically will insert some values into a database but before doing so I need to do a number of different checks on an alternative database, if anything doesn't check out I want to return the client with a NON 200 http status code but which should I use?
What is the recommended status code to return? I would also like to return some text with it which would contain additional information that could identify what the error was.
Or is it recommended to return 200 and an additional JSON payload identifying if there was a problem and what it is
Does anyone have any examples??
Thanks in advance
400 BadRequest could be used if what you are performing is validation logic and this validation logic fails for some reason. As far as the additional information is concerned, you might return some info in the body, for example as JSON payload:
{
"errorMessage":"Validation failed because user doesn't exist in alternative database"
}
If on the other hand you are attempting to update an entity that doesn't exist, you could also send a 404 status code.
In addition to what Darin stated on this thread, here is a good reference on status codes. I have also found this article valuable in handling errors with ASP.NET WebAPI.