Response code for POST method should be 201 not 200
Response code for POST method should be 201 not 200
An old issue from LoopBack3: https://github.com/strongloop/loopback/issues/360
We should fix it in LoopBack4 as well.
Notes from the spike
-
Users should be able to customize the status code from the response object returned by the controller method, otherwise we should default to 201 - this will be implemented by #436.
-
There are two approaches we can choose as implementation, but based on the spike findings and the consensus, pursue option 1 from below:
- option 1: return the status code and header from the result of controller method directly
- ~option 2: read the status code from OpenAPI spec and write it into the response in
rest/src/writer.ts~, see the spike PR https://github.com/strongloop/loopback-next/pull/1260 - There is already some comparison and discussion for the two approaches in PR https://github.com/strongloop/loopback-next/pull/1260 to start with, chose one approach and implement it.
Acceptance criteria
- [ ] Modify controllers in the
example/*projects so thatcreate*methods (typically mapped toPOSTverb) return201 Createdinstead of `200.- Update the OpenAPI Spec description of operation result, replace 200 to 201
- Update the controller method implementation to return status code 201 and set
Locationheader to the URL where the newly created model instance can be found
- [ ] Update CRUD Controller template used by CLI similarly
- [ ] If https://github.com/strongloop/loopback-next/issues/2736 has been done, then update the extension accordingly too.
Thanks to reactivate this important point !
I think this has two parts:
-
We need to figure out how to allow controllers to specify response status code (and response headers, while we are at this)
-
The CRUD controller template (see https://github.com/strongloop/loopback-next/issues/727) and the CRUD controller base class (see https://github.com/strongloop/loopback-next/pull/740) should return 201 from
createoperation
hi team, we are upgrading from swagger2 to openapi3, PR is ready for it https://github.com/strongloop/loopback-next/pull/916
There is an interface change of the responseObject in openapi3, I think it's better to implement this story for v3 directly instead of implement it with v2 then take another effort to upgrade to v3, thanks!
Does the alteration to the responseObject formatting change the logic required to handle the return code in some way? I would've expected that the sequence would simply handle the success of a POST with a 201 code in the same way for v2 and v3; that is, I'd expect a property with the same name (probably statusCode) at the top level.
@kjdelisle good point, honestly I am not sure, and due to the effort needed in v2-v3, see comment:https://github.com/strongloop/loopback-next/issues/753#issuecomment-362054454, the PR won't be landed in a few days, so no sense to block this story :)
@kjdelisle and me decided this does not really belong to MVP/Walking Skeleton.
So, can you give a status of this issue please ? can we expect a fix on 4.x ? whatever the version of Open Api specification, have a correct code for POST still make sense ;-) But I'm not at the right position to mesure the effort... so it's easy to ask !
Marking the item as non-MVP doesn't mean that we won't be doing it for the 4.x release, it just means that it's not a part of our initial push to get the framework into a stable state.
Our goal with the idea of MVP is that we want the framework to be in a position where:
- Community members can begin learning how it works in earnest
- Community members can begin to contribute fixes, as well as new features or plugins
The MVP is not the final release! It's an interim state between the constant flux of alpha and the near-completeness of a beta. We've set this goal to help stop us from getting too far ahead of ourselves with respect to what we want to see in the final release vs. what should be there at a minimum.
Ok fine ! thx
Hi, any news on this topic please ?
@Cooker-Monster checking with my team, will let you know the update then.
@jannyHou , you've mentioned that this is related to the openapi-v3 work that you're doing. Could you please add more details? Thanks.
@Cooker-Monster @dhmlau sorry for the late reply!
I think there are two things related to the status code:
- Generate the OpenAPI
responsespecification
- It would happen in
openapi-v3, see generating operation spec in filecontroller-spec.ts, we can detect the operation type and generatingresponseaccordingly. E.g. If an operation ispost, the successful status code for it is201. schemacan be generated based on the controller function's metadata. This is off topic here, but to generate a complete response spec(it has to be complete, otherwise it's not a valid v3 spec), we need bothstatuscodeandschema, and also the content type.
- Write the http response according to the
resultfrom the controller method.
- It can use the OpenAPI path spec as the reference to decide the status code, which means it reads the
201as the successful status code for a post method, write it to http response. - This would happen in
restpackage,src/writer.tsfile.
While I appreciate some opinion from @bajtos in case my understanding of 2 is not correct.
Discussing with @raymondfeng yesterday, the goal here is that given the default response code being 200, how we can let users to customize the response status code and even body. One possibility is to see what we can do with the @post decorators.
I don't think this task has a clear acceptance criteria. Moving it back to needs discussion column.
I can't figure out how tricky this point is inside the existing code (I'm mainly an enthusiastic user of the framework) but to sumup my way of thinking, every time I want to promote Loopback to dev teams, I'm facing a little desapointment when POST returns 200 in my demo. So debate is always fructeous, but I would like to find a quick workaround to fix this important point.
Few more ideas to consider:
When returning 201 Created, the response should include a Location header providing a URL of the newly created entity to clients. See https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2, emphasis is mine:
The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field.
If we had support for configurable response types/formats already implemented (see https://github.com/strongloop/loopback-next/issues/436), then the problem with 201 status code could be solved by changing the template of create controller methods to something like below:
@post('/products')
async create(@requestBody() obj: Product)
: Promise<ControllerResponse<Product>> {
const model = await this.productRepository.create(obj);
return {
statusCode: 201,
// FIXME: Do not hard-code `model.id`, find the actual PK property name.
// FIXME: Can Location contain a path only, with no hostname and scheme?
headers: {location: `/products/${model.id}`},
body: model,
}
}
I created a PoC PR for approach "reading success statusCode from response spec": https://github.com/strongloop/loopback-next/pull/1260, summarized our discussion in it. Maybe we can continue discussion in that PR then post a solution here.
cc @raymondfeng @bajtos @strongloop/sq-lb-apex
FWIW, the latest version of HTTP/1.1 spec allows the Location header to contain a relative path.
See https://tools.ietf.org/html/rfc7231#section-7.1.2, emphasis is mine:
The "Location" header field is used in some responses to refer to a specific resource in relation to the response. The type of relationship is defined by the combination of request method and status code semantics.
Location = URI-referenceThe field value consists of a single URI-reference. When it has the form of a relative reference ([RFC3986], Section 4.2), the final value is computed by resolving it against the effective request URI ([RFC3986], Section 5).
See also https://en.wikipedia.org/wiki/HTTP_location.
Seems to be a duplicate of #436.