JSON API response for a collection POST that couldn't be performed - json-api

I am building an API where one can issue a POST to /users/1/suggestions/make in order to get a new suggestion. There are two cases:
the server can create a suggestion based on POSTed params, in which case a 200 status code is returned together with the created suggestion;
the server cannot create a suggestion based on POSTed params, in which case I am not sure what status code to return (200, since the request succeeded but nothing could be suggested, 404 because a suggestion could not be computed, or something else) and what content (nil, an empty response, something else).

If your POST is unsuccessful due to the parameters not passing validation, it is appropriate to return HTTP 400 Bad Request. The response body should consist of a list of the errors that caused the rejection.
This way it is clear to the API caller that no data has been modified.

Related

How to get the response object when status >= 300 using http-client call-with-input-request?

How do I get the response object from call-with-input-request when the HTTP status is >= 300?
The docs say this about call-with-input-request:
Returns three values: The result of the call to reader (or #f if there is no message body in the response), the request-uri of the last request and the response object. If the response code is not in the 200 class, it will raise a condition of type (exn http client-error), (exn http server-error) or (exn http unexpected-server-response), depending on the response code. This includes 404 not found (which is a client-error).
This means that call-with-input-request signals a non-continuable condition, which (as far as I understand) means that the function does not return, and I cannot get access to the response object that would otherwise be returned. Therefore I don't see how I can actually get access to the response object corresponding to this request.
I still want to be able to inspect the response, even if its status is in the 30x-50x range. For example, I want to be able to print the HTTP reason string, or log it for debugging later. How can I achieve this?
If you trigger the exception from the REPL, you can inspect it with the ,exn comma-command. Then you'll notice the condition has a response property which is a contains the status code, headers etc.
The docs could be improved in this regard I'm sure. Perhaps you have a suggestion where to put this? The problem is that the exact contents of the condition object depend on where the condition was thrown, so not all properties will always be available.

Tracing an HTTP request in Go in a one structured log line

I have learned you can "decorate" the HTTP transport so that you can details of the request, however I can't quite figure out how you log the URL in the same line.
https://play.golang.org/p/g-ypQN9ceGa
results in
INFO[0000] Client request dns_start_ms=0 first_byte_ms=590 response_code=200 total_ms=590 url=
INFO[0000] 200
I'm perpetually confused if I should be using https://golang.org/pkg/context/#WithValue to pass around the context in a struct, especially in light where https://blog.golang.org/context-and-structs concludes with pass context.Context in as an argument.
Go through the behaviour of how the request is constructed in request.go from net/http. You see that the RequestURI field is never set there. Quoting from same reference,
Usually the URL field should be used instead.
It is an error to set this field in an HTTP client request
So, I would suggest you to use request.URL instead.
It is a parsed from the request uri. It should have the data you need.
You can construct the output as following:
f := log.Fields{
"url": fmt.Sprintf("%s %s%s", r.Method, r.URL.Host, r.URL.Path),
}
Also, in my experience, it is far more easier to use context.WithValue and pass the context as an argument.
Replace r.RequestURI by r.URL.String() in your code to log the full, valid URL (https://golang.org/pkg/net/url/#URL.String). RequestURI is empty on the client side (https://golang.org/pkg/net/http/#Request), as the output from your code is showing.
I don't see how context.Context relates to your question, but I believe https://blog.golang.org/context-and-structs is considered "best practice".

Proper REST response for empty table?

Let's say you want to get list of users by calling GET to api/users, but currently the table was truncated so there are no users. What is the proper response for this scenario: 404 or 204?
I'd say, neither.
Why not 404 (Not Found) ?
The 404 status code should be reserved for situations, in which a resource is not found. In this case, your resource is a collection of users. This collection exists but it's currently empty. Personally, I'd be very confused as an author of a client for your application if I got a 200 one day and a 404 the next day just because someone happened to remove a couple of users. What am I supposed to do? Is my URL wrong? Did someone change the API and neglect to leave a redirection.
Why not 204 (No Content) ?
Here's an excerpt from the description of the 204 status code by w3c
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
While this may seem reasonable in this case, I think it would also confuse clients. A 204 is supposed to indicate that some operation was executed successfully and no data needs to be returned. This is perfect as a response to a DELETE request or perhaps firing some script that does not need to return data. In case of api/users, you usually expect to receive a representation of your collection of users. Sending a response body one time and not sending it the other time is inconsistent and potentially misleading.
Why I'd use a 200 (OK)
For reasons mentioned above (consistency), I would return a representation of an empty collection. Let's assume you're using XML. A normal response body for a non-empty collection of users could look like this:
<users>
<user>
<id>1</id>
<name>Tom</name>
</user>
<user>
<id>2</id>
<name>IMB</name>
</user>
</users>
and if the list is empty, you could just respond with something like this (while still using a 200):
<users/>
Either way, a client receives a response body that follows a certain, well-known format. There's no unnecessary confusion and status code checking. Also, no status code definition is violated. Everybody's happy.
You can do the same with JSON or HTML or whatever format you're using.
I'd answer one of two codes depending on runtime situation:
404 (Not Found)
This answer is pretty correct if you have no table. Not just empty table but NO USER TABLE. It confirms exact idea - no resource. Further options are to provide more details WHY your table is absent, there is couple of more detailed codes but 404 is pretty good to refer to situation where you really have no table.
200 (OK)
All cases where you have table but it is empty or your request processor filtered out all results. This means 'your request is correct, everything is OK but you do not match any data just because either we have no data or we have no data which matches your request. This should be different from security denial answer. I also vote to return 200 in situation where you have some data and in general you are allowed to access table but have no access to all data which match your request (data was filtered out because of object level security but in general you are allowed to request).
If you are expecting list of user object, the best solution is returning an empty list ([]) with 200 OK than using a 404 or a 204 response.
definitely returns 200.
404 means resource not found. But the resource exists. And also, if the response has 404 status. How can you know users list empty or filled?
'/users' if is empty should return '200'.
'/users/1' if the id is not found. should return 404.
It must 200 OK with empty list.
Why: Empty table means the table exists but does not have any records.
404 Not Found means requested end point does not exist.

Is it considered bad practice to perform HTTP POST without entity body?

I need to invoke a process which doesn't require any input from the user, just a trigger. I plan to use POST /uri without a body to trigger the process. I want to know if this is considered bad from both HTTP and REST perspectives?
I asked this question on the IETF HTTP working group a few months ago. The short answer is: NO, it's not a bad practice (but I suggest reading the thread for more details).
Using a POST instead of a GET is perfectly reasonable, since it also instructs the server (and gateways along the way) not to return a cached response.
POST is completely OK. In difference of GET with POST you are changing the state of the system (most likely your trigger is "doing" something and changing data).
I used POST already without payload and it "feels" OK. One thing you should do when using POST without payload: Pass header Content-Length: 0. I remember problems with some proxies when I api-client didn't pass it.
If you use POST /uri without a body it is something like using a function which does not take an argument .e.g int post (void); so it is reasonable to have function to your resource class which can change the state of an object without having an argument. If you consider to implement the Unix touch function for a URI, is not it be good choice?
Yes, it's OK to send a POST request without a body and instead use query string parameters. But be careful if your parameters contain characters that are not HTTP valid you will have to encode them.
For example if you need to POST 'hello world' to and end point you would have to make it look like this: http://api.com?param=hello%20world
Support for the answers that POST is OK in this case is that in Python's case, the OpenAPI framework "FastAPI" generates a Swagger GUI (see image) that doesn't contain a Body section when a method (see example below) doesn't have a parameter to accept a body.
the method "post_disable_db" just accepts a path parameter "db_name" and doesn't have a 2nd parameter which would imply a mandatory body.
#router.post('/{db_name}/disable',
status_code=HTTP_200_OK,
response_model=ResponseSuccess,
summary='',
description=''
)
async def post_disable_db(db_name: str):
try:
response: ResponseSuccess = Handlers.databases_handler.post_change_db_enabled_state(db_name, False)
except HTTPException as e:
raise (e)
except Exception as e:
logger.exception(f'Changing state of DB to enabled=False failed due to: {e.__repr__()}')
raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, detail=e.__repr__())
return response

Why is request method send to web server called GET and POST?

I guessed that the name of each of the request method has a relationship with the operations they performed in some manner. But I can't get it!
Detials:
GET means posted argument are showed in the url and POST means they are sent but not shown in the url. But what is that related to POST/GET? What is gotten/posted or what does the posting/getting job? Do you have any glues?
I understand what GET and POST method is. What I wanna know is why do we GET/POST, why don't we call it TYPE1/TYPE2, or another more make-sense name like ON-URL/OFF-URL
Please discuss if you know that.
This should help you:
Methods GET and POST in HTML forms - what's the difference?
http://www.cs.tut.fi/~jkorpela/forms/methods.html
The Definitive Guide to GET vs POST
http://carsonified.com/blog/dev/the-definitive-guide-to-get-vs-post/
get and post
http://catcode.com/formguide/getpost.html
From RFC 2616:
GET
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.
POST
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.
So, GET should be used to read a resource, whereas POST should be used to create, update, or delete a resource.
GET and POST are called HTTP Verbs. See the RFC for details.
GET will get a resource identified by a URL. If using GET as the action for a form the entries will be encoded in the URL (look at a google search for an example).
POST will send the data separately, to the specified URL.
The biggest difference is that if you use GET on a form submit, you can copy the URL of the page you landed at and use it directly to get the same results. All information will also be visible in the URL (don't use this method for passwords). If you POST the data the URL of the landing page will not be enough to reproduce the same results; you will have to go through the form again.
Take a look at the RFC definitions here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
But essentially, GET is used to retrieve a resource and POST is used to create a new one or make a change to a resource.
Seems to me that #Nam G. VU is asking an English-language question.
"Get" implies that the flow of data is from the server to the client. More specifically, the client is asking the server to send some data.
"Post" implies that the client is pushing data to the server. The word "post" implies that it's a one-way operation.
Of course, neither of these is 100% unidirectional: GETs can send data to the server in the
URL as path and/or query arguments, and POSTS return data to the client.
But, in the simplest sense, the English verbs imply the principal direction of data flow.
From the REST standpoint, GET METHOD signifies that it is used to GET a (list of similar) resource(s). POST is used to create (or POST) a resource.
Apart from this, GET carries all parameters in the URL in the format of ?name=value& pairs, whereas POST carries all of them in the Request Body.

Resources