Breezejs sending over multiple entities - php

I'm using BreezeJS w/ a PHP backend API and am curious if two or more entities are being created at the same time that have a relationship with each other - if they all get sent to the server at the same time when the request is sent to the server - how do you:
Know which item needs to be created first for the relationship constraints to succeed
If one entity is created successfully, but there is some problem w/ the other entity (ie: 400, 401, 500, etc...) what would be an appropriate response to send back in the response?
This is what my current request looks like:
Is there a better way to break these up and if so - does breeze (with its knowledge of metadata) know to send requests in the appropriate order?

Related

How to create a compound object in a REST API

I'm creating a REST API for my application, and I have a doubt about how to design my API, following REST principles. I'm using PHP and Lumen, but I guess it's more a design doubt than a technical one.
Consider I have two entities:
Company:
- id
- name
User:
- id
- name
- email
- company_id
Each Company must have one or more User's, and I'd like to assert that rule in my API. As far as I've understood REST specifications, I should create one endpoint for each entity, so the API client should make a POST to http:\\myserver\api\company to include a company, and after that make another POST to http:\\myserver\api\company\{id}\users to include a User in the new Company. The problem with that approach is that the client could only create a Company and leave it without User's.
In a non-rest API, I could create a method called createNewUser, which would receive the user's data together with Companydata, and this method would ensure that both entities are created.
How could I achieve that in a REST API?
I have a doubt about how to design my API, following REST principles.
Part of the problem here could be the confusing messages you are getting about "REST principles".
Consider how you might do this on the web. You want somebody to give you both user data and company data. So you would create a web page with a form; some of the form controls would be designed to collect user data, some would be designed to collect company data. When the form is submitted, the browser would copy the information from the forms input controls into an application/x-www-form-urlencoded request body, and POST it to the target URI specified in the metadata of the form. Ta-da.
That's REST.
Is that the only answer that's REST? No. Equally RESTful would be to have clients write the user and company data into a local document, and then save a copy of that document on the web server. Or to download a document from the web server, edit the user and company data into the local copy, then save the revised document on the server. Or to send a patch document describing the edits to the web server, and allow the server to compute the changes to its own copy of the document.
All of these are fine.
as I've understood REST specifications, I should create one endpoint for each entity,
This is where you are getting derailed (not your fault, the literature sucks)
REST doesn't have endpoints, it has resources
HTTP requests target resources, not entities
"different entity therefore different resource" is not a constraint that comes from REST.
Fine grained resources work well in some cases (in particular they are a good fit for copying information into an anemic data model), but they aren't universal. In a context where fine grained resources don't work well... design your resource model differently.

API REST returning new resource when updating existing one

I have a ProjectStep resource in my application and I have to create an API endpoint that will be used to update my ProjectStep to mark it as finished and create the next ProjectStep. In my REST API I could just do something like this :
PATCH /project-mark/1
POST /project-mark
But I would like to use only one request to update the current step, create a new one and return the newly created ProjectStep.
What method would you use? A PATCH request updating an existing resource and returning a different resource doesn't sound like a good idea.
Thank's
Use a PUT request, please see this link
https://stackoverflow.com/questions/630453/put-vs-post-in-rest
Use PUT APIs primarily to update existing resource (if the resource does not exist then API may decide to create a new resource or not). If a new resource has been created by the PUT API, the origin server MUST inform the user agent via the HTTP response code 201 (Created) response and if an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

delay websocket updates and show the message later on?

I have an app where basically players challenge each other. At some point their challenge completes and I need to provide them (both of them - there are two players) with an update message, like 'Hey, you won and got 100500 points'. And vice versa - "Hey You looose"
I use websockets and pusher api to tackle the live updates, this works perfectly when player is "online". But what if they are not? The way to go for me looks like I can still handle the event with pusher and instead just displaying the message, I can store it to db to table challenge_notifications with fields messages and seen = 0. it's ok, but what would be the best way then to show this to the player when he comes online next time? I don't want to have ajax request on every page load checking to see if there are any unseen notifications for the user.
I probably somehow need to fetch all pending notifications only once, when they get online?
I use Laravel 5 for my backend.
There was a recent post on the Pusher blog about how to detect if a user is online or not using the Pusher HTTP API: Enabling Smart Notifications with Pusher and SendGrid.
The example uses SendGrid, but you could instead store the update to a database, send them a Push Notification, an SMS etc.
what would be the best way then to show this to the player when he comes online next time?
I guess there are two forms of "coming online":
The user is no longer on the site and has to navigate to the site. In that case as the page loads you can query the DB and serve them up any missed notifications directly (this would seem the easiest solution). Or, if it fits your app architecture, make a single AJAX request when the page loads to get any missed notifications.
If the user has gone offline due to them being mobile or having a bad network connection. In that case you can bind to the connected event using pusher.connection.bind('connected', function() {}); and then make a query to see if they've missed any notifications.
In summary: it would seem that querying the DB for any missed notifications upon normal page render (on the server) would be the simplest solution and wouldn't required much resource usage. But there are alternative mechanisms of delivering a notifications (email, SMS) if they're not online.

Best methods of implementing a sync api

I searched everywhere for this but couldn't get a proper answer.
I'm building a client app (angular) and an api (php). Periodically the server and the client's indexed db needs be in sync.
What i have done so far.
once every 10 minutes the clients makes a post ajax call to the server api
it send two prams. a. array of data which is a log of changes made to the documents . b. an array of ids which the server should return its documents
the server will copy all the data in the array to a collection for later processing. and will return a list of id which successfully copied. the server will also return the documents for the requested array of ids
back in the client the angular app will update the documents the server responded and will save the successfully saved ids to the indexed db which will again be send int the next api call.
This is a very simple routine. i just wanna know are there any other methods or standards?
you need to use $timeout or $interval service. if you are using $timeout service in the succuess callback again initiate $timeout service to the api kind of recursive, this will update the same scope model every time and your UI will be updated according to the latest data

Public API design - handling failure with a http code? Is that REST?

I am just about to make a webservice available for fellow programmers in my sector using PHP on my own server.
As this is the first time I have done this, I first investigated APIs that I frequently use, Flickr etc.
My service returns granular data extracted from a very large csv file by examining GET arguments, it is read-only.
The data is returned in a variety of formats, xml, json, jsonp etc.
example of the call: /?offices=ABC|XYZ&format=xml
Firstly, I'd like to know if I am I correct in terming my service an "API"?
Also I would also like to know how best to handle failure.
I return straight text messages in the case of a user not submitting the expected input - "you failed to submit any offices".
In the case of any other unforeseen malfunction, at the moment it returns a failure message in payload of the chosen format, eg json with the single array "fail" in it and I have documented this.
Having read up a little on REST recently, when a failure is not caused by misuse of the "API" - should I return something other than HTTP code 200?
If you were accessing this service, what would you prefer to see?
Should I make this another GET option?
e.g /?offices=ABC|XYZ&format=xml&on_failure=http
Or am I getting muddled between the terms API and REST?
SO suggested this post, which deals with 400/401
What's an appropriate HTTP status code to return by a REST API service for a validation failure?
but I am looking for clarification about the terms I am using. If the payload contains the error message - as in the case of Flickr then why should I wander away from that?
The larger providers like Flickr and Twitter have muddied the definition of REST quite a bit. Many developers now mistakenly believe that any service or API over HTTP is "RESTful." What you describe here is more of a data Web service using a form of RPC. Truly RESTful APIs use fluent HTTP and Web standards, and are resource centric.
To answer the main question about HTTP status codes, I would say that for RPC services it's not necessary, as the HTTP status codes won't always directly translate to method call errors. A better approach would be to map your own error codes and return them along with the status message.
For example, an RPC service for user lookups may return the following on success:
SUCCESS=1
USERNAME=example
FIRSTNAME=Example
LASTNAME=User
DISPLAYNAME=Example User
The same service may return the following on failure:
SUCCESS=0
ERRORCODE=1002
ERRORMSG=User subsystem error; requested user was not found.
In an RPC service, the exact details of the response are very flexible. All it does is relay the results of the method call to the invoker. As long as you document what the developer should see, and return clear and consistent messages, it'll work out just fine. The only HTTP status codes an RPC service should return are 200 and 500 (and only then when things break so badly you can't even return a proper error).
Back to the matter of REST, the same user service can be made RESTful if we think of a user as a resource and use an appropriate URL scheme. The very, very basic makeup of a RESTful API are as follows:
GET /api/users - should return a list
of available user accounts in the
system.
GET /api/users/example - should return
details of the example account;
returns a 404 HTTP status if the user
does not exist.
POST /api/users - create a new user
account; should return a link to the
newly created account (ways of doing
this vary, but the LOCATION header
makes sense here). Various HTTP status
codes may be returned depending on the
result.
PUT /api/users/example - edit the
details of an existing user account.
Various HTTP status codes may be
returned depending on the result.
DELETE /api/users/example - delete an
existing user account. Various HTTP
status codes may be returned depending
on the result.
The standard HTTP status codes most common to RESTful interfaces are below.
200 OK - The request was successfully completed. If this request created a new resource that is addressable with a URI, and a response body is returned containing a representation of the new resource, a 200 status will be returned with a Location header containing the canonical URI for the newly created resource.
201 Created - A request that created a new resource was completed, and no response body containing a representation of the new resource is being returned. A Location header containing the canonical URI for the newly created resource should also be returned.
202 Accepted - The request has been accepted for processing, but the processing has not been completed. Per the HTTP/1.1 specification, the returned entity (if any) SHOULD include an indication of the request's current status, and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.
204 No Content - The server fulfilled the request, but does not need to return a response message body.
400 Bad Request - The request could not be processed because it contains missing or invalid information (such as validation error on an input field, a missing required value, and so on).
401 Unauthorized - The authentication credentials included with this request are missing or invalid.
403 Forbidden - The server recognized your credentials, but you do not possess authorization to perform this request.
404 Not Found - The request specified a URI of a resource that does not exist.
405 Method Not Allowed - The HTTP verb specified in the request (DELETE, GET, HEAD, POST, PUT) is not supported for this request URI.
406 Not Acceptable - The resource identified by this request is not capable of generating a representation corresponding to one of the media types in the Accept header of the request.
409 Conflict - A creation or update request could not be completed, because it would cause a conflict in the current state of the resources supported by the server (for example, an attempt to create a new resource with a unique identifier already assigned to some existing resource).
500 Internal Server Error - The server encountered an unexpected condition which prevented it from fulfilling the request.
501 Not Implemented - The server does not (currently) support the functionality required to fulfill the request.
503 Service Unavailable - The server is currently unable to handle the request due to temporary overloading or maintenance of the server.
Hopefully this information is useful, and not overload. :-)

Categories