I am implementing a patient portal where patients can book an appointment based on Hospital schedules slots availability. Process is implemented in a Request->Response synchronous model, so once Appointment Resource is sent using POST to create the appointment, synchronous response knows if appointment is accepted and booked.
Which must be the body response in this situation:
1- No body and just HTTP Status 200
2- HTTP Status 200 and Body with the created Appointment
3- HTTP Status 200 and Body with an AppointmentResponse
Thanks,
Option #2: HTTP Status 200 and Body with the created Appointment
Appointment response comes from the invitees later
Related
I have a HTML form, which I submit via http post.
There are two cases:
Case 1: The data is valid and data on the server will be updated accordingly
Case 2: The data is invalid and the http response contains an error message for the user.
Which http status codes should be used for each case?
I use htmx to submit the form. This means I don't need to use the POST/Redirect/GET pattern.
This question is not about JSON-APIs.
The complete list of HTTP response codes published by the Mozilla Foundation is pretty comprehensive and easy-to-read, so I'd recommend always consulting it as a guide. For the generic use-cases mentioned by you, there are a couple of different codes you can return - depending on what happens with the data on the server, and what you want to happen in the user's browser.
CASE 1: data is valid, data on server is updated
Base on your short description, the different status codes that might be applicable are:
200 (OK): you are updating an existing record on your own server - eg., the user is submitting a form which updates their existing contact information on your website - and information was received, and the record updated successfully. The response would usually contain a copy of the updated record.
201 (Created): you are not updating an existing record, but rather, creating a new record on your server - eg., your user is adding a new phone number to their contact details, which is saved in your database as a separate 'phone' record. The response should contain a copy of the newly created record.
205 (Reset Content): the same as 200, but implies that the browser view needs to be refreshed. This is useful when the record that is being updated has values that are dynamically calculated by the server, and which might change automatically depending on the values you're submitting. For example, if you have a user adding extra information to their online profile, which might grant them special status, badges and privileges on the website. This means, that if the user is viewing their profile information, that information will need to be updated with the new 'status' automatically granted by the server. The 205 response body will normally be empty, which means that to update the browser view your response-handling code will need to:
do further ajax requests and update the relevant part(s) of your
interface with new information from the server, or
redirect the user to a new URL, or
reload the entire page.
If working with HTMX, a 200 or 201 response would include the actual html snippet of the record that you want updated on the page - and HTMX will replace it automatically for you when it receives the response. With a 205 response, you could send an HX-Trigger response header that would call a custom event on the interface elements that need to update themselves - see the examples in the docs.
CASE 2: data is invalid, data on server is not updated
The status code that needs to be returned in case of an error varies depending on what caused the error. Errors that the server believes are the responsibility of the client - such as 'sending invalid data' - have a status code in the 4XX range. Some of the common errors in that range include 404 ('Not Found'), 403 ('Forbidden'), and 'Unauthorised' (401).
In the case of a client sending data that the server cannot process because it is 'not valid' - either because the request itself is malformed, or because the data doesn't pass some business validation logic - the current advice is to return status 400 (Bad Request).
Many years ago, some people believed that the status code 400 should only be used to indicate a malformed request (syntactical error) - not to indicate a failure in business validation logic (semantic error). There was a lot of debate, and temporarily a new status code (422) was created, that was supposed to cover semantic errors, exclusively. In 2014, however, the official definition of the status 400 code was changed to allow for the inclusion of both syntactical and semantical errors - which rendered status 422 essentially unnecessary.
You can find lots of discussions and explanations online about the differences between 400 and 422, and some people still argue passionately about this to this day. In practice, however, the 400 code is all you'll need - and you can include a response body in it that explains in detail, if needed, the cause of the error.
Note that when working with HTMX, a response with a 400 code should trigger an htmx:responseError event automatically. You can trap that event, for example, to update your form interface elements, in case of data validation errors caught by the server.
Well, 200 OK and 201 Created are the best for successful result.
For invalid data I would return 422 Unprocessable Entity, because the headers are correct, but body is not (though parseable by the server). The caveat is some HTTP clients won't handle 422 properly and in this case you have to use 400 Bad Request, however, the most of the modern clients will be fine.
You have said it is not about JSON APIs, but how will you meet this type of requirement - it is not clear whether this is relevant for your scenario???
SERVER DRIVEN BEHAVIOUR
I cannot see how a client could ever decide an HTTP status code based on input data. How would the client deal with these examples?
The call is not authenticated (cookie or token) - an API would return 401 - this tells the UI to perform a retry action.
The call is not authorized - an API would return 403 or 404 and the UI would present an error display.
The data is malformed or invalid according to domain specific checks - an API would return 400 and tell the UI what is wrong so that it can perform actions.
Something went wrong in server processing, eg data cannot be saved because database is down.
MY THOUGHTS
htmx looks interesting but a key requirement before using it would be ensuring that htmx can read server side error responses and use values returned. Maybe there is an elegant way to do this ...
Maybe I am just paranoid :). But it is worth being careful when choosing technologies that there are no blocking issues. Lack of error handlng control would be a blocking issue in most systems.
I'm using htmx 1.8 with asp.net core 6.0.
This works for me.
controller:
//server side validation failed
Response.StatusCode = 422;
return PartialView("Core", product);
client side javascript:
document.body.addEventListener('htmx:beforeOnLoad', function (evt) {
if (evt.detail.xhr.status === 422) {
//
// allow 422 responses to swap as we are using this as a signal that
// a form was submitted with bad data and want to rerender with the
// error messages
//
evt.detail.shouldSwap = true;
evt.detail.isError = false;
}
});
200 OK or 201 Created are the best choice for a successful POST request.
However, for invald data, you can pass 415 Unsupported Media Type
I am using the EWS Managed API to create appoitments on Exchange 2010.
Appointment appointment = new Appointment(exchangeService);
appointment.Subject = "Sample meeting";
appointment.Body = "Sample meeting body";
appointment.Start = bookingInfo.from;
appointment.End = bookingInfo.from.AddMinutes(bookingInfo.duration);
appointment.Location = meetingRoom.displayName;
appointment.Resources.Add(<my_room_mail>);
// Send the meeting request to all attendees and save a copy in the Sent Items folder.
appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
This piece of code create effectively an appoitment in my Outlook but the Meeting Room included as a resource is marked as a "tentative" (not really accepted). So when I want to delete the meeting, the meeting room stay booked (busy/tentative) for the slot and it is impossible to delete the tentative.
If I delete the appoitment from the EWS code (using the appoitment ID), it works as expected, the room is effectively free.
Appointment appointment = Appointment.Bind(exchangeService, new ItemId(itemId));
appointment.Delete(DeleteMode.MoveToDeletedItems);
Do you have any idea of what is the problem ? Outlook right ? Bad appoitment creation or resource booking ?
Ok, I understand that Direct Booking is not compatible with EWS/OWA/Mobile solutions (and also with Outlook 2010/2013 without register tweak).
Direct Booking and Resource Booking Attendant (Auto Accept feature) are conflicting technologies, and if enabled together, unexpected behavior in calendar processing and item consistency can occur.
Check this for more details :
http://msexchangeanswers.blogspot.fr/2009/08/outlook-direct-booking-vs-auto-accept_17.html
http://exchangeserverinfo.net/2013/05/remove-auto-accept-from-outlook-for-all-room-mailbox/
The resource room needs to auto-accept the invitation, so it loses its tentative status. Then when you delete the appointment from your calendar, it should automatically send cancellation to the room. There is a setting on the delete to do this, and I forget off the top of my head if it's the default or not, but I think the initial issue is why the room is not configured to accept or reject the invite sent.
I have to write an application which serves HTTP request.
For these requests application has to send the response content with status**.
Status is integer which represents status code.( 1 : Session Expired, 2: Invalid Request Data. etc,.)
There are 2 options.
One is to send the status code with content itself:
Ex : {status : 56, content: [{name:'pinto', id: 90}]}
Another one is specifying the status code in header itself, so that once I receive the header from client if status states the there is an error I can abort the request so that I don't have to receive the response body and process it.
I think second option will be better than first one, because
No need to get for the response content which is very much helpful in case of content is large.
Is this is recommended solution or any other suggestions ?
You should be using HTTP status codes for this kind of thing.
Session Expired: 401 Unauthorized - authentication is possible but has failed
Invalid Request Data:
400 Bad Request - request cannot be fulfilled due to bad syntax
405 Method Not Allowed - request method not supported by that resource
409 Conflict - request could not be processed because of conflict
413 Request Entity Too Large - request is larger than the server is willing or able to process
422 Unprocessable Entity - request unable to be followed due to semantic errors
i am working on status update and commenting application in asp.net mvc3 like Facebook wall and comment. User can comment my wall and all stuff like Facebook.
http://demos.99points.info/facebook_wallpost_system/
like above demo, i want to create my application.
how can i do that using mvc3 and ajax?
i successfully updated user status to database but cant get all status updates of same user, i want to use partial view to display all status of user below the status textarea.
and if user write some status and share status that time status message saved in database and again reflect to same view Asynchronously.
how can i do that using ajax?
I'm going to answer this in broad terms as I don't have any knowledge of asp.net or mvc3. However, it seems to me that you're looking for more architectural direction.
You will need to setup an endpoint which generates the status page, call it /status.asp. This will create the text area and load the existing status messages from your database.
Then create a second endpoint, say /api/status.asp. This is not a view, but an API in your application that let's a user create (and, if you want, retrieve/modify/delete?) a status.
When a user hits enter in the textarea, fire off an XHR request to /api/status.asp with the new status. It is common, but not required, to do this as a POST request (read up on REST - http://en.wikipedia.org/wiki/Representational_State_Transfer). This API should then save the new status to your DB, and return the uid of the status along with the status message, perhaps as JSON (or XML or YAML if you prefer, it's up to you). For example, in JSON:
{
status: [
{
uid: '1234567890987654321'
msg: 'Hello World'
}
]
}
(To send the XHR request it's easiest to use a JS library like Dojo ( http://dojotoolkit.org/reference-guide/dojo/xhr.html#dojo-xhr ) or JQuery ( http://api.jquery.com/jQuery.ajax/ ).)
When your XHR request returns, check the status is a 200 (everything went OK), then read the data returned. Write some Javascript to create a new DOM node, inject the status message into that DOM node and add it to the bottom of the previous status nodes.
Bonus Points:
If you want person B to be looking at person A's /status.asp page and for that page to auto-update when person A posts a new status, you'll need to do a little more work. Firstly, modify /api/status.asp to return a list of the last x (say, 10?) status updates when called via HTTP GET. Include the UID of each status along with the status text.
Call your /api/status.asp API repeatedly* (perhaps with a timestamp of the last time you called it, and get your API to only return status posts after that time), loop over the the results and check to see if that post is already included in the users page (perhaps by having an id on each DOM node matching the UID of the status). If not, add it to the page.
*you have a number of options for doing this. For example, simply setup a JS timeout (easy, but not very efficient), or use Comet (eg http://cometd.org/) or WebSockets ( http://websocket.org/ ). I'd go for a timeout first, get it working and then figure out if a better technology is required.
If a website user submits an HTML form with: (1) a post method; (2) a multipart/form-data enctype; and, (3) a large attached file, can the server upload a posted file, and send a server generated HTTP response before the file upload is completed, without using AJAX?
That's pretty dense. So, I wrote an example to illustrate what I mean. Let's say there is an image upload form with a caption field.
<form action="upload-with-caption/" method="post" enctype="multipart/form-data">
<input type="hidden" id="hiddenInfo" name="hiddenInfo" />
File: <input type="file" name="imgFile" id="imgFile" /><br />
Caption: <input type="text" name="caption" id="caption" />
<input type="submit" />
</form>
I want to store the caption in a database table with the the definition:
[files_table]
file_id [uniqueidentifier]
file_caption [varchar(500)]
file_status [int]
Then I want to upload the file to /root/{unique-id}/filename.ext.
file_status is mapped to a C# enum with the following definition:
enum FileUploadStatus{
Error = 0,
Uploading = 1,
Uploaded = 2
}
When the form submits, if the file is too large to process in 1 second, I want to send the webpage back a response that says it is currently uploading.
Can I do this with a single synchronous HTTP post?
Note: I will obviously want to check for the status updates later using AJAX, but that is not what this question is asking. I am specifically asking if the file can continue to upload after the response is sent.
HTTP is a synchronous protocol.
You cannot send a response until you receive the entire request.
Looking at the HTTP specifications alone (RFC's 753x), then the answer is Yes (and, the currently accepted answer is wrong). HTML specifically I don't think have anything to add.
The HTTP/1.1 protocol "relies on the order of response arrival to correspond exactly to the order in which requests are made on the same connection" (RFC 7230 §5.6). Timing has nothing to do with it.
Not only does the protocol allow for early responses, but some message semantics from categories 4xx (Client Error) and 5xx (Server Error) actually expects the response to be sent before the request has completed.
Let's take an example. If you intend to send five trillion billion million gigabytes to a web server (let's assume this number fit whatever data types are in use for the Content-Length header), when would you expect to receive a "413 Payload Too Large" response back? As soon as possible or only after a couple of decades when the request transfer completes? Obviously the sooner the better!
2xx (Successful) responses are a bit different. These responses "indicates that the client's request was successfully received, understood, and accepted" (RFC 7231 §6.3). Sending back this type of response early is likely to confuse the client.
Instead, what you probably want to send back as an early response belongs to the 1xx (Informational) category. These are referred to as "interim responses" meant to supersede but not obsolete the final response.
RFC 7231 §6.2:
The 1xx (Informational) class of status code indicates an interim
response for communicating connection status or request progress
prior to completing the requested action and sending a final
response.
RFC 7230 §5.6:
More than one response message per request only occurs
when one or more informational responses precede a
final response to the same request.
RFC 7231 §5.1.1 has a great example where a client is about to send a "presumably large" message but instead of immediately sending the body after the head, the client includes an Expect: 100-continue header and then goes into a short paus whilst expecting the server to either reject the message or welcoming the client to carry on by means of responding a "100 Continue" interim response. This then potentially avoids the client having to transmit bytes for nothing. Smart!
Finally, I thought long and hard about when would we ever want to send a 2xx (Successful) response back to the client before the request has completed? I can only come up with one single scenario - and this is certainly not a common case, but I am going to have it stated: If the server has consumed enough of the request in order to take action and the server wish to discard the remaining body because the residue is sufficiently large and at the same time of no more use to the server, then respond 202 Accepted and include a "Connection: close" header.
This is obviously not good for connection re-use and could also easily lead to confused clients and so the payoff why we're responding early should be 1) advantageous enough to mitigate the overhead of establishing a new connection, 2) advantageous enough to offset the danger of crashing clients that was not prepared for an early response, and 3) be well documented.
The "Connection: close" header will explicitly instruct the client to stop sending the request (RFC 7230 §6.3). And due to message framing, the connection is dead anyways as there is no way for the communication to resume with a new message exchange pair over the same connection. Technically speaking, the client can cleanly abort a chunked transfer (RFC 7230 §4.1) and thus save the connection, but this is details and not applicable in the general case.