2 questions about RESTful Web Services

2019-07-30 15:45发布

问题:

I am new to RESTful web services. I have the following 2 questions:

  1. Are GET, POST, DELETE, PUT, TRACE, HEAD, OPTIONS, the only verbs in Http that I can use for RESTful web services?

  2. How do I create and use a custom verb?

I'm using Java and Jersey for creating my RESTful web services.

回答1:

The answer to question 1 is, yes as they are restricted by the HTTP specification. However as a matter of practice, most REST applications use only GET and POST, as these are most widely supported by all of the Internet infrastructure. And then the answer to question two is no, you can't create a custom verb.

The thing you have to consider in your use of the HTTP verbs is that a GET should have no side effects, as the client is free to resend a GET at any time (in the event a communication failure was detected). A POST however can be sent by the client at most once, so this should be used for anything that causes a change that cannot be repeated (like an insert).

Normally you would define what "verb" you want in your application as part of the URL, not as the HTTP verb.



回答2:

Then how do I provide the 10 actions with only 7 verbs?

The idea behind web services is to focus on the objects, not the verbs.

Your actions either "Create" ("POST"), "Retrieve" ("GET"), "Update" ("PUT") or "Remove" ("DELETE") the objects.

Doesn't each action go under a separate verb?

No. You can have all the objects you want. You only need four verbs to create, find, change and remove objects.

Or I'm wrong and can use conditionals to provide several actions under a single verb?

No. You can make a create ("POST") request which can, in turn, create a number of individual objects.

In general how do others design their application such that they don't need extra verbs even if they need to provide a 100 different actions?

You focus on the objects. Objects are created, retrieved, updated and deleted.