For a REST API I'm developing, a client is able to register a company, which subsequently needs confirmation/activation through email. After the following example request is received, an email is sent with an activation link in it, to activate the account.
POST /companies HTTP/1.1
<company>
<name>CoolCompany</name>
<email>coolcompany@example.com</email>
</company>
If the above request was successful (valid data, email successfully sent), the company resource is saved in the database, but will only be available at /companies/<id>
(given an appropriate Authorization header) after confirmation is received.
Given this scenario, is
HTTP/1.1 202 Accepted
// Perhaps optionally with a Location header,
// of where the resource will be available, as well?
Location: /companies/<id>
an appropriate response? Or would
HTTP/1.1 201 Created
Location: /companies/<id>
be a more appropriate response?
REST is an entity based consept. If I got a 201 Created response, this would intuitively suggest that the resource has been created and is available, which is not this case. The resource is first available after the confirmation, and I would therefore suggest using the 202 Accepted header.
In addition, you can not be sure that the user has received the email at the request time. I like using 202 Accepted in cases like these (SMS, Email etc), because it tells the API consumer that it was a valid request, but it might take some time before it is done.
My idea is:
201 - is when all the stuff/processing is completed in the end of request (DB populated, files created etc), so when client (event immediately) GET the resource, he will receive it complete.
202 - is when request is received and successfully started processing but according to some restrictions of process no all request related activities processed.
In you case:
if send email synchronously and don't return response until email sent, than I guess 201(Created) is OK
if for example you set email sending task into queue and return to client immediately and email may be sent a little bit later (or for example there is some manual processing of new clients by operator before sending email) than 202 is better.