How design restful api for sending email to users - rest

Sending email including new password to user is provided by rest api.
for example, after call "user/{email}", user will receive the email to get new password.
I think sending email is not kind of GET, PUT, POST, PUT.
How design url to more perfect restful api.

I think sending email is not kind of GET, PUT, POST, PUT.
That's true, but that's not what you are doing. You are sending a document to the server to advance a protocol, that has a side effect of sending an email. See Jim Webber
HTTP is an application protocol whose application domain is the transfer of documents over a network.
For the case of performing a password reset, you probably want clients to recognize that the operation is not safe. So you should prefer POST or PUT to GET.
On the web, where we are using HTML representations of resources, POST is the only option available to us, and it works just fine.

There is a lot of missing information here but have a look at Send Grid's API. I know this isn't a direct answer to your question, but I cannot leave comments.

Related

What is the best REST API design that enables a resource to be sent by email?

I'm designing a REST API for an ordering system using the CRUD paradigm.
My routes are as follows:
- GET orders
- POST orders
- GET orders/{order}
- PATCH orders/{order}
- DELETE orders/{order}
This makes perfect sense to me, however, each order can then be sent by email once it has been reviewed and I'm not 100% sure what way to approach it.
I had thought of using:
- POST orders/{order}/sendemail
but then I think I'm using POST incorrectly because it's used for creating resources. Also the route now has a verb in it, which isn't ideal for a resource based REST API.
Then my next thought was to use:
- POST emails/orders/{order}
but that would then imply that emails are a resource which they aren't.
Or should I be using a combination of routes and query strings?
POST orders/{orders}?send-email=true
What would be the best way?
I think I'm using POST incorrectly because it's used for creating resources. Also the route now has a verb in it, which isn't ideal for a resource based REST API.
Both of those ideas are wrong. POST doesn't mean create, it means POST. See also Fielding 2009
POST serves many useful purposes in HTTP, including the general purpose of "this action isn’t worth standardizing."
REST doesn't care what spelling conventions you use for your resource identifiers; as an experiment, see if the following links work the way you expect:
https://www.merriam-webster.com/dictionary/get
https://www.merriam-webster.com/dictionary/post
https://www.merriam-webster.com/dictionary/put
https://www.merriam-webster.com/dictionary/patch
https://www.merriam-webster.com/dictionary/delete
Presumably, you don't want to send emails any time a web crawler happens to come by, indexing your resources, or when a smart cache tries to optimistically load all the links that it knows about, so you are going to want to consider unsafe methods.
POST is the most straight forward choice
POST /??? HTTP/2.0
Content-Type: text/plain
Hey Bob,
Please send the email for order #12345
Riddle: if all of the information that you need is in the body of the HTTP request, does it matter what the target-uri in the request-line is?
Answer: yes! It matters because caching; the target-uri for the request also identifies that document that should be invalidated in the cache if the request is successful.
In other words, we want to look for some related resource (document) whose representations will be changed if the request is successful. In this specific case, that might be a document that somewhere in its representation includes the status of the email itself.
The most obvious candidate? The resource for the order itself
POST /orders/12345 HTTP/2.0
Content-Type: text/plain
Hey Bob,
Please send the email for order #12345
You can also use a remote authoring idiom; the basic idea being that the client edits the document, and then the server figures out what to do based on the edits. For example
GET /???
200 OK
Content-Type: text/plain
Order #12345
Email:
Status: PENDING APPROVAL
PUT /???
Order #12345
Email:
Status: APPROVED
And then its up to the server to diff the two different representations of the resource, and figure out that the status changed and therefore the email should be sent.
Again, you've got some freedom about what /??? should be - is it the same document as the order itself? is it some other document? is that other document in a subordinate location to the order document, or in some other part of the hierarchy?
Neither REST nor HTTP cares very much, other than noting that if the resource identifiers are different, then they are different documents with independent caching policies.
Your problem is that you are trying to think of how you request an email in REST terms as a resource, but you said yourself that emails aren't a resource. It sounds like emails are an indirect result of some sort of state change (the review and approval of an order).
Maybe it makes sense to have order approvals as a resource. If the email generation is tied to the approval process you can have;
/approvals/orders/{order}
With a POST operation to create an approval for the order. This would trigger the email.
Alternatively, if the status is tied into the order you might have;
/orders/{order}
with a PUT operation to update a status field from pending to approved and this would trigger the email.

HTTP method for both sending and returning information

I'm building a web application that needs to process some information on a server. There is no database involved, the server (using Flask) just needs to receive some (complex) information, process it, and send back the result.
My question is which HTTP method is most suitable here (if any). When I read about HTTP methods, they are usually explained in terms of a REST api, where a GET request is used to retrieve data from the server and a POST request is used to create new data on the server. In my case however, I don't need to store any information on the server. A GET request doesn't seem suitable here, as the information sent to the server is rather complex, and can't be easily encoded in the URL. I think a POST request should work here, as I can send the data in JSON format, but the specifications say POST should be used when you want to create something on the server, and a response should only contain a success message and/or location.
Am I missing something here? Should I use something different like WebSocket, or is a POST request fine here, although it doesn't abide by the REST principles?
Thanks in advance.
the specifications say POST should be used when you want to create something on the server
No, they don't. A lot of people say that, but the specification is not so restrictive.
The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics
Here's how Roy Fielding explained it in 2009:
POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.”
Yes, POST isn't ideal - the semantics of POST are neither safe nor idempotent, and your particular case would benefit from communicating those properties to general purpose components.
But it is good enough, until the work is done to standardize the semantics of a new method token that better handles this case.
We use POST method to send data to the server. What the server does with the data is encoded in the server logic.
As a client if you want to just send data to server use POST.

When is JSON-RPC over http with POST more suitable than RESTful API?

I'm currently developing a web application with a senior developer. We've agreed to use REST API for client-server communication and he sent me the parameters and the expected responses.
But the design does not seem to be RESTful. Rather it looks like JSON-RPC over http utilizing only the POST method.
For example, to register a user you send a POST request to the server the following parameters.
{
id: 1,
method: "RegisterUser",
params: {
firstName: "John",
lastName: 'Smith',
country: 'USA',
phone: "~",
email: "~",
password: "~"
}
}
And the expected response is
{
id: 1
result: "jwt-token",
error : null
}
Multiple requests are sent to the same URL and the server sends back the response based on the 'method' in the parameters. For example, to get a user info, you send a { method: "GetUserInfo", params: { id: ~ }} to the same URL. All responses have the status code 200, and the errors are handled by the error in the response body. So even if the status code is 200, if error is not null it means something is wrong.
The way I'm used to doing is sending a POST request to 'users/' with a request body when registering a new user, sending a GET request to 'users/1' to retrieve a user information, etc.
When I asked why he'd decided to do it this way, he said in his previous job, trying to add more and more APIs was a pain when following RESTful API design. Also, he said he didn't understand why RESTful API uses different HTTP verbs when all of them could be done with POST.
I tried to come up with the pros of REST API over JSON-RPC over http with POST.
GET requests are cached by the browser, but some browsers may not support POST request caching.
If we are going to open the API to outside developers, this might cause discomfort for them since this is not a typical REST API.
In what circumstance would the JSON-RPC over http style be better the REST RESTful APIs? Or does it just not matter and just a matter of preferance?
it looks like JSON-RPC over http utilizing only the POST method.
Yes, it does.
The way I'm used to doing is sending a POST request to 'users/' with a request body when registering a new user, sending a GET request to 'users/1' to retrieve a user information, etc.
That's not quite it either.
Riddle. How did you submit this question to stack overflow? Well, you probably followed a book mark you had saved, or followed a link from google. Maybe you submitted a search or two, eventually you clicked the "Ask Question", which took you to a form. After filling in the details of the form, you hit the submit button. That took you to a view of your question, that include (among other things) a link to edit the question. You weren't interested in that, so you were done -- except for refreshing the page from time to time hoping for an answer.
That's a REST api. You, the agent, follow links from one state to another, negotiating stack overflows "submit a question" protocol.
Among other things to notice: the browser didn't need to know in advance what URLs to send things to, or which http method to use, because the HTML had encoded those instructions into it. The browser just need to understand the HTML standard, so that it could understand how to find the links/forms within the representation.
Now, REST is just a set of architectural constraints, that boil down to "do it the way a web server does". You don't need to use HTML as your media type; you don't need to design for web browsers as your clients. But, to do REST, you do need hypermedia; and clients that understand that hypermedia type -- so it is going to be a lot easier for you to choose one of the standardized media types.
Are there more reasons why I should prefer RESTful API over JSON-RPC over http with POST? Or does it just not matter?
Roy Fielding, in 2008, offered this simple and correct observation
REST is intended for long-lived network-based applications that span multiple organizations. If you don’t see a need for the constraints, then don’t use them.
For instance, the folks working on GraphQL decided that the properties that the REST constraints induce weren't valuable for their use case; not nearly as valuable as being able to delivery to the client a representation tuned to a clients specific needs.
Horses for courses.
Use RESTful APIs when you are performing standard create, read, update and delete actions on resources. The CRUD actions should behave the same way for each resource, unless you have some before and after hooks. Any new developer coming to the project will easily understand your API if it follows the standards.
Use JSON-RPC when you are performing actions that don't necessarily map cleanly to any CRUD. For instance, maybe you want to retrieve counts or summary data of a specific resource collection. You could do this with REST, but it might require you to think of it as some sort of "summary" resource that you read from. It's easier to do with JSON-RPC, since you can just implement a procedure that runs the appropriate query in your database and returns an appropriate result object.
Or what if you want to make an API call that lets a user delete or update all of instances of a resource(s) that meet some condition, without knowing ahead of time what those instances are?
You can also use JSON-RPC in cases where you need to have a lot of side effects for standard CRUD actions and it's inconvenient to make hooks that run before or after each action.
You don't have to go all in with one of the other, you can use both. Have standard RESTful endpoints where appropriate and another RPC endpoint for handling JSON-RPC calls.
Use REST when you write public web services. REST is standardized and predictable, it will help consumers to write client apps. Also, GET HTTP method is widely used to retrieve resources from public web services.
Use JSON RPC when you write back-end for an application (i.e. not public web services). JSON RPC style is more flexible and more suitable for register, login, and getProductsByFilters methods. There is no reason to use GET with JSON RPC, only POST should be used.

REST API - Post Requests to Query Active Directory

My company is currently writting a REST API where they allow querying for Active Directory specific information via a POST requests.
In the request body the following information gets sent to the API:
Filter (LDAP)
Properties to return (e.g userAccountControl, sAMAccountName)
From a personal point of view I would have definitely realised it via simple GET methods.
Is the POST method approach the recommended way to so? Are there any particular reasons to implement it with POST?
I can see slight advantages of using a POST request. It is certainly more secure for sending any sensitive data, because the body of the request is not cached by the user's browser and other network devices on the way. Also a POST request allows you to send an unlimited amount of data, but that is probably not relevant for this use case.

API Key in path

We have some IoT sensors that POST json payloads to an endpoint. They are configured with only a HTTPS URL to send to, no ability to setup authentication etc.
We need basic ability to see which sensor is sending data, and loosely prevent anyone from sending payloads. Full authentication will not be possible.
It was suggested we could put a token in the path and use it as a super basic API Key. I was wondering what the best format for the route should be...
/api/events/_ingest/api-key
/api/producer/api-key/events/_ingest
I was wondering what the best format for the route should be: /api/events/_ingest/api-key or /api/producer/api-key/events/_ingest
There's no best approach here, both are really bad. The API key does not belong to the URL. It should be sent in the standard Authorization HTTP header.
Once you mentioned in the comments that it will be something temporary, you could try a query parameter. It's still bad though. But you will be able to reuse this same route later, just moving the API key to a HTTP header, when your clients support it:
/api/events/_ingest?api-key=somecoolhashgoeshere