Apigility code-connected service - for POST method - rest

I am a newbie to the apigility code-connected service & was able to create a RESTful service with fetch and fetchall class method on the mapper file.
Can someone point me a good sample for insert (POST) data via REST service ?
Thank you,
Kevin

POST is going to be used for creating a new resource typically. This means that in your request you're going to want the following headers:
Accept: application/json
Content-Type: application/json
The first tells Apigility what sort of a response it is expecting. The second says that the data you'll be providing to the API will be in json format.
Apigility uses json or json+hal by default for a return and expects json for the incoming data.
When you're creating a new resource, typically you'll be persisting it in a database and as such the id of the resource will be generated by your code or database. The rest of the resource will be provided by the caller to the API. Example:
POST /api/user
{
"username": "kevin voyce",
"firstname": "kevin",
"lastname":" "voyce"
}
If you do this, you should see a response of something like
405 - Method Not Allowed
The body of the error should indicate that the method has not been defined. The error message is coming from the create method in the resource. Inside this method, you'll see an argument called $data which at this point will consist of a PHP stdClass with fields matching the stuff you passed in via the JSON body.
This is where the fields part of configuring your API in Apigility comes in. If you set up the names of the fields and put validators on the fields, Apigility will make sure that the fields that are passed in conform to and are valid according to these validators before the call is made into your API. The same applies to not just POST, but PATCH and PUT as well. This means that within your methods you don't have to worry that the input hasn't been validated (as long as you correctly configured your validators).

Related

Different response for same API but different method (GET and POST)

I think this is a classic and typical question but I didn't find its answer.
In my knowledge, the POST method is used to send data to the server with request parameter in message body to make it secure. And GET method is to retrieve data with parameters in the URL.
But what I didn't understand is how the same api may have different behavior by just changing the method.
Here is an example. I use SoapUI 5.5.0, this is the link of the api: https://reqres.in/api/users/1
when I use GET method I get this:
{
"data": {
"id": 1,
"email": "george.bluth#reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
}
}
and by changing only the method to POST, I get this:
{
"id": "244",
"createdAt": "2020-02-27T14:30:32.100Z"
}
(the id and date changes each time)
as described in this link https://reqres.in/ that it is creating an instance and we can add parameters..
BUT, can any one explain how is it technically possible to have different behavior with different methods on the same URL.
In my knowledge, the POST method is used to send data to the server with request parameter in message body to make it secure. And GET method is to retrieve data with parameters in the URL.
That's probably getting in your way.
HTTP Requests are messages; each message starts with a request-line
method SP request-target SP HTTP-version CRLF
The request-target identifies the target resource upon which to apply the request
The method token indicates the request method to be performed on the target resource.
You can think of it being like a function call
GET(target-resource)
POST(target-resource, message-body)
Or equivalently you can think of the resources as objects that share an understanding of message semantics
target-resource.GET()
target-resource.POST(message-body)
But what I didn't understand is how the same api may have different behavior by just changing the method.
The same way that an api can exhibit different behavior by just changing the request-target.
In HTTP, the request-line is literally human readable text that the server will parse. Having parsed the request-line, the server program can then branch to whatever code it wants to use to do the work, based on the values it found in the message.
In many frameworks (Spring, Rails) the branching logic is provided by the framework code; your bespoke handlers only need to be correctly registered and the framework ensures that each request is forwarded to the correct handler.
how is it technically possible to have different behavior with
different methods on the same URL
for the technical possibility, you can look at the spring framework's answer to this.
You can have a controller that is accessible on a single url but can contacted in four says, GET, PUT, POST, DELETE. To do this, Spring provides the annotations #GetMapping, #PostMapping, #PutMapping, #DeleteMapping.
All the requests are sent to the same url and Spring works out which method to call based on the verb.
In Restful APIs, verbs have very important meaning.
GET: Retrieve data
POST: Create a new entity with the request's body
PUT: Replace an entity with the request's body
PATCH: Update some properties of an entity with the request's body. A.K.A. Partial update
In your case, changing the verb from get to post has the effect of creating a new entity with ID 1. That's why you get a response with the newly created ID and a createdAt timestamp.

Delphi datasnap REST server PUT & POST management

Relation between REST CRUD operation and HTTP verbs are described at:
Using HTTP Methods for RESTful Services
Also, at Embarcadero REST overview it is covered with exmples:
REST overview
However, in implementation of mapping PUT and POST there is inconsistency:
Datasnap REST
Implemented behavior treat PUT as method for inserting new resource, and return code: 201(Create), but POST, as "update" prefix for related method suggest: return 200(OK).
If we put aside inconsistency in prefix of methods for PUT and POST and force regular return response code for insert new resource:
// User inserted in DB, obtain UserID
LUserID := LspUserInsert.FieldByName('UserID').AsString.Substring(1,36);
// Response on a new User inserted
with GetInvocationMetadata(True) do
begin
ResponseCode := 201;
ResponseContentType := 'application/json; charset=utf-8';
end;
//TODO: Set Location in the response header
GetDataSnapWebModule.Response.Location := LHTTPReq + '/' + LUserID;
end;
Is there better way to implement regular mapping of PUT and POST? Also, how to get additional information for Location in the header of the response for 201(Create):
http://[host]:[port]/[request_path]...
so, the insert method can create in the response header (for example):
Location=http://localhost:8080/datasnap/rest/TTestServerMethods/Users/D813258D-F3D3-42D3-8C5B-9D392442C8D0
Edited:
Sorry for incomplete information and using not so clear terms "better way" and "additional data".
I would like to solve the following issues in a more elegant way, if there is any:
Change method name. (Status: partially solved) Procedure for insert an user is named "updateUsers" due to datasnap REST prefix for POST which I want to use for create resource. The only was is to choose different name of method, but then REST request has to put method name in quotas ("insertUsers").
Generate expected response on datasnap REST request. (Status: SOLVED) Default behaviour of PUT on ok response is always 201(Create), and POST responds with 200(OK). Attached part of code solved 201(create) response.
So problem is partially solved, with additional code, consent to weird methods names or request that clients create requests with quoted resources. I believe that there is a "better way" to solve present datasnap REST implementation of PUT and POST, by means of override some methods of classes doing implementation of datasnap REST. I hope Embarcadero will fix this REST "misinterpretation" in following releases.
About Location. Usually, POST creates a resource and responds with 201(create) with accompanied location of created resource in the response header. In mentioned method I get created userID from a stored procedure, however I need data coming from HTTP request URI( host, port, path_to_resource), to create complete Location string. For above example, this "additional data" is: "http://localhost:8080/datasnap/rest/TTestServerMethods/Users/"

The difference between XPOST and XPUT

I am learning Elasticsearch, I found that XPOST and XPUT are in general the same when 'update' or 'replace' documents. They all change the field values.
curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '
{
"name": "Jane Doe"
}'
curl -XPOST 'localhost:9200/customer/external/1/_update?pretty' -d '
{
"doc": { "name": "Jane Doe" }
}'
So they all changed the name field to "Jane Doe". I am wondering whats the difference between XPOST and XPUT in the above context.
The two commands are not at all the same. The first one (with PUT) will update a full document, not only the field you're sending.
The second one (with POST) will do a partial update and only update the fields you're sending, and not touch the other ones already present in the document.
firstly, -X is a flag of curl.
please see -X in the man page. It is same as --request. You can specify which HTTP method to use (POST, GET, PUT, DELETE etc)
http://curl.haxx.se/docs/manpage.html
Regarding POST and PUT, they are HTTP methods or "verbs".
ElasticSearch provides us with a REST API. According to REST practices, POST is for create and PUT is for updating a record.
Please see:
http://www.restapitutorial.com/lessons/httpmethods.html
HTTP PUT:
PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one. PUT is idempotent, but paradoxically PUT responses are not cacheable.
HTTP 1.1 RFC location for PUT
HTTP POST:
POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource. The POST method is not idempotent, however POST responses are cacheable so long as the server sets the appropriate Cache-Control and Expires headers.
The official HTTP RFC specifies POST to be:
Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Extending a database through an append operation.
HTTP 1.1 RFC location for POST
Difference between POST and PUT:
The RFC itself explains the core difference:
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
Using the right method, unrelated aside:
One benefit of REST ROA vs SOAP is that when using HTTP REST ROA, it encourages the proper usage of the HTTP verbs/methods. So for example you would only use PUT when you want to create a resource at that exact location. And you would never use GET to create or modify a resource.
upvote if it helps you :)
PUT method is idempotent so if you hit payload with put method, it will create first time only and if you hit the same request again and again, it won't create new records, it will simply update the previously created.
On the other hand if you hit the payload with POST method no of times you will create a no of entries of same payload.

How can I create a resource list on Apigility?

So, I have a create method on Apigility to create a resoure which is basically a
POST /resources
{
<fields go here>
}
... and I was wondering how can I also have the option to create a list of these resources.
From what I can see these are my options:
replaceList: PUT /resources
patchList: PATCH /resources
but I'm not sure which kind of payload I should send. Should I send an array of resources or an object with an array of resources?
If you create a DbConnected Service, see this code https://github.com/zfcampus/zf-apigility/blob/master/src/DbConnectedResource.php.
This methods are not implemented by default.
If you create a code connected service, you can send any payload. The data will be parsed as a array to you make what you want.
I don't know the behavior of validation on these requests.
If you send a array of entities, the Apigility 1.0.4 will validate each entity (see this link), maybe you have to write especific validators to each HTTP METHOD, or relax the general validator (see this link).
This link has some suggest to your payload https://apigility.org/documentation/api-primer/halprimer.
In your case I would use a array.

Passing parameters in BODY with GET request

I want to pass some data within request body, but I'm using GET request, because I just want to modify this data and send it back.
I know that it is bad practice to use body with GET requests.
But what should I do with this situation if I want to build correct RESTful service?
P.S. I'm not changin any object on server.
I'm not putting any new object on server.
You want a POST. Something like
POST /hashes
{
"myInput": ...
}
The response would be the hashed value. There's no rule that the created resource must be retained by the server.
From the RFC:
The action performed by the POST method might not result in a
resource that can be identified by a URI. In this case, either 200
(OK) or 204 (No Content) is the appropriate response status,
depending on whether or not the response includes an entity that
describes the result.