Making an existing API more RESTful [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've an existing API, which I'm attempting to make more RESTful.
The app involves a Gifter and a Giftee. The Gifter buys something for the Giftee, and sends the link to the gift on whatsapp.
Before creating a user account for the Giftee, I first do some verification by tying the person to a phone number. I've 2 endpoints:
/sendSmsCode
/verifyUser
First endpoint sends an sms code to the phone number, and second endpoint takes the sms codes and verifies its correct. /verifyUser then returns a session token. This session token is then used to accept the gift and create the user.
Obviously these are not RESTful endpoints. But the user hasn't been created at this stage so I can't do something like /users/{id}/send-sms (which I know wouldn't be too RESTful either given it includes a verb).
Any suggestions?

I meant to post a comment, but it's overly long for a comment, so I'm posting it as an answer (although it may not answer your question directly).
Obviously these are not RESTful endpoints.
REST is an architectural style and not a cookbook for designing URIs. It's never enough to stress that REST itself doesn't care about the URI spelling, as long as the URIs comply with the RFC 3986.
To be considered RESTful, an application must follows a set of constraints defined in the chapter 5 of Roy Thomas Fielding's dissertation.
You mention use use a session token in your question. If the session state is kept on the server, than it's not RESTful at all. REST applications are meant to be stateless, where one request contains all required information to be understood by the server, without taking advantage of session state stored on the server.
I can't do something like /users/{id}/send-sms (which I know wouldn't be too RESTful either given it includes a verb).
One important concept of the REST architectural style is the resource and their identifiers.
The URI (or Universal Resource Identifier) is meant to identify a resource rather than expressing the operation over the resources. The operation to be performed over the resource can be expressed by the request method. The request method is the primary source of request semantics, indicating the purpose for which the client has made this request and what is expected by the client as a successful result.
To properly identify resources, it's a natural choice using nouns (as the verb is expressed by the HTTP method). But it's not mandatory to use only nouns. As long as you comply with the REST constraints, you surely can design a RESTful API with some verbs here and there (and possibly use POST for sending data to such endpoints).

Related

Which 4xx http status code for REST [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
We have a RESTful architecture and I have a question regarding to exceptions and http statuses for our API.
We use 400 for cases:
value mismatch (for instance, expected 100 but was 99)
violations of #Size, #Min, #Max, #Nullable anc etc
Use 422 (unprocessable entity) for cases when something wrong with logic, but it is not a client mistake. For example, trying to set category to product which already has one. This is unpredictable on the client side.
Finally, we use 409 (conflict) for cases when it is a client's error.
For example, if he is trying to send invalid Date format via JSON. Or registration date is far away before current.
But one case fits into a few categories:
We have a Tax field which is integral number.
If client sends fractional Tax then exception should be thrown.
From one side, this is clearly 400 and client should see 'Tax cannot be fractional'.
But, from other side - it is a client's programmer error, since he is trying to send Double/Float instead of Integer/Long (i.e. he sends another type, it's like pass Long instead of String) and 409 should be thrown.
What should I choose: 400 or 409 for TypeMismatch in Numbers case?
And if 400, why should I make an exusement for Number types but throw 409 for Date/String cases of TypeMismatch?
I would prefer answers with a definite logic rather then a "I think". This is not a discussion.
I concur with the opinion-based question comment, but I'll also throw this out there:
Opinion: Since types are more fundamental I would throw a 409
Honestly I would prefer status code 400 or 422 for your use case since the provided entity can't be processed because of its content. This can be something structural (wrong types, missing required fields, ...) or data validation (wrong format using regexp, not allowed values, duplicate values, ...).
Status code 409 should be rather used for optimistic locking, as described in the link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html:
10.4.10 409 Conflict
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
Hope it helps you,
Thierry
I don't see why you would a 409 for any of these cases.
Here is what Wikipedia says about 409:
Indicates that the request could not be processed because of conflict
in the request, such as an edit conflict in the case of multiple
updates.
I would use 400 for the number types as well as the Date/String case.
But it is a matter of personal flavor, both status codes are possible as long as you stay consistent throughout your API.

PayPal-Java SDK/Credit card payment issue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My question is about the way how credit card payment is realized by PayPal API
Particularly I'd like to ask about this code snippet from GitHub:
https://github.com/paypal/PayPal-Java-SDK/blob/master/rest-api-sample/src/main/java/com/paypal/api/payments/servlet/PaymentWithCreditCardServlet.java
Credit card object is prepared, all necessary credentials are typed in, including the amount to be payed, sender's billing address and name, etc.
The only thing I cannot understand from this, is why there is no receiver specified ?
That's basically all
Am not a Java dev -
The "receiver" is "your" (merchant) REST application (which is tied to your PayPal Account) you setup in the Developer Console. You authenticate when making requests - in this specific case, you are sending a credit card for auth/capture in one step (aka sale).
So "you" (the authenticated App) are/is the "receiver".
Think of this process as the API Credentials in the PayPal Classic APIs. Hth....
Update:
so you mean that the token belongs to "receiver", not "sender" ? as well as those client ID and client secret ? i thought they belong to sender
"You" - your app, is the sender (in Paypal's context). Your app sends payment information to Paypal for processing. To do that, PayPal must know "who" you are (which Paypal/merchant account/app) is sending the request.
What exactly are you referring to as "receiver" - maybe it's just terminology that's getting in the way?
Update 2:
by receiver I mean the party that gets the charged amount
"Receiver" == funds: In this specific example/code you referenced.Your app/you merchant account that made/sent the request (your app is sender and "receiver" per this definition).
This is a standard "business"/merchant payment processing flow. Forget the tech/API, think about a POS in a restaurant. That POS (aka "app") will send card data (from swiping a physical credit card) to some processor it has an account at, using whatever protocols it needs to communicate with that processor.
If you're actually looking for some "send money to someone" flow (not the code you referenced), this is probably what you're looking for. This has a different meaning for "receiver" - aka "recipient(s) of funds". I don't actually use it, but it seems straightforward...
Hth..

Defensively checking inputs in client. Is this a good practice? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Is it a good practice to defensively check for null/empty inputs in client ? In the server this check is happening of whether or not input is null and an exception is thrown accordingly, should client also make a check in order to avoid a call to the webservice ?
Under the best circumstances, it is a performance improvement, and nothing else.
Under the worst circumstances, the client side checking can drift away from what the server accepts, actually introducing bugs due to inconsistent deployments.
In either case, you don't typically have control over the client environment, so you cannot assume the client-side check was performed. Malicious users can inject their own client-side code which will permit non-valid inputs to be sent to the server, so server-side checking is still strongly required.
I would recommend that you do client-side checks, but I would also recommend that you take the care to ensure that your client-side checks are synchronized with your server-side checks, such that your client doesn't start filtering inputs in a different manner than your server would. If that becomes too problematic, error on making the server side checking correct. It's the only real defense point.
It's good practice to do whatever you need to do to protect your server, whatever that may be.
Always do checking server side, you never know where data is going to come from.
Do checking client side if you have some reason for notifying the user of their mistake before sending data to a server. For example, a client-side validation of an integer input can, e.g., update a warning label as the user is typing without requiring round-trip validation to the server. Client-side checks are essentially a first line of action for displaying clear validation errors to the user, but really they are nothing more than UI performance improvements. If you don't want to do that, then you don't need to do that. If you only want to do that for certain values, you only need to do that for certain values.
Perhaps your server already generates reasonable information about validation errors, in which case you could display those to the client. It really depends on your situation and needs.
For example, lets say the client displays a series of dialogs asking for input before finally sending a request to the server. It's irritating for the user if they aren't notified of an invalid input until after they go through the entire series of dialogs. This is a good case for client-side validation at each step of the input.
Note that the cost of client-side validation is that you need to make sure to maintain it to match the actual server-side rules if they change.
It's also good practice to think a little about your specific requirements and choose an appropriate course of action to make sure those requirements are met, rather than asking vague questions about generic, situation-agnostic "good practice".
Personally, I try my best to have server-side validation report useful information, and I don't do any initial client-side validation. I then add client-side validation later, after higher priority work is complete and after determining that the UX would clearly benefit from it.
Yes, in order to keep the bandwidth and the server load as low as possible, you should always add client-side validation as well. Even a thin-client can do easy validations like null/empty-checks.
If you have some complex validation depending on many different inputs (cross-validation) or maybe complicated checksum calculations, you might skip the client-side validation and do it only on server side.
Server side validation is always needed though, because as you can see, the client cannot be trusted if you would now decide to not validate.

The role of the Service Class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I know there's quite a bit out there on this topic, but I couldn't seem to find any that completely answers my questions. I was told to use a Service->DAO->Low level code architecture . I'm having a hard time wrapping my head around is the exact role of the Service class, will one Service class work for a Book DAO and also a user DAO? I was going to have a Service class for each, haveing the Service clas talk to the DAO, take the resulting string and store it in my Book class and User class, then send that object back to the Controller. In my thinking, the Service class is the high level class that delegates all the work to other classes. Thanks for your help.
A collection of service classes, known as a service tier, is responsible for carrying out the business logic of an enterprise application. Service classes usually don't map directly to DAOs, since they represent business operations that might involve a large number of domain objects. An example is an order-submission process, where the code responsible for accepting an order has to work with the objects representing orders, customer accounts, financial accounts, and inventory.
Separating the various business operations into different service classes is a design decision that depends on the complexity of the operations, how closely they're related, and so on. Some designers might decide that each business operation should be essentially a separate class (similar to the Command pattern), while others prefer a more comprehensive interface with a richer variety of methods.
The concept of a service tier exists to make sure that all of the business logic is stored in one place and not duplicated. Many modern systems will have several interfaces into the backend, such as a Web application (perhaps with Spring MVC Controllers), a SOAP or REST interface (perhaps with Jersey), and specialized adapters for legacy terminals or other systems. Making these interfaces all adapters around a common service tier ensures that they all behave in a consistent way and that any changes to the service tier are applied to all of the access interfaces.
In your particular case, since you're needing to ask, a single service object will probably be sufficient for your needs. It's always a good idea to list all of the service methods on a separate interface and code to that so that you can replace the implementation for testing or future upgrades.
Service class may be acting as a layer of abstraction so DAO or data layer is hidden from the "business layer".
The service may talk to multiple DAOs to perform a function in which case it's acting more of a Facade pattern, hiding the complexity of communicating with DAOs to perform the required functionality.
This sort of pattern is seen in the port and adapter or hexagonal architecture in that the business logic is insulated from lower level protocols.
http://c2.com/cgi/wiki?PortsAndAdaptersArchitecture

What is the purpose of javax.servlet.FilterChain? [duplicate]

This question already has answers here:
What is the use of filter and chain in servlet?
(3 answers)
Closed 9 years ago.
I inherited a Struts 1 app that heavily utilizes FilterChain and I don't understand the benefit of this extremely obfuscating code.
"In the Servlet API, you normally use a Servlet when you want to control, preprocess and/or postprocess specific requests. But when you want to filter/modify common requests and/or responses based on specific conditions, then a Filter is much more suitable."
Every request in my app is based on specific conditions, e.g., a merchant id or a search term. But it seems like placing a request inside a whole chain of stuff that completely hides what is going on from the developer trying to trace the cause of an error, is nuts.
The FilterChain#doFilter() call just continues the HTTP request to the destination, following exactly the same path as if you didn't use a filter in first place. This is usually a servlet class or even a JSP file. So, in order to debug problematic code, better put a breakpoint in the target code, not in the filter if it doesn't contain any code of interest.
My coworker (who's not registered on SO) explained that it's for applying global functionality to an app that you don't want to do in every single controller, such as checking if the user is logged in.

Categories