Quantcast
Channel: Mobile App Development & Design Company – Snyxius
Viewing all articles
Browse latest Browse all 167

Guide to Rest API Best Practices V.2

$
0
0

1

This article is a continuation of previous articles on REST API best practices. In this article, we will offer a new best practice of REST API with a greater detail.

So, without wasting any time lets dive into some new REST API best practices.

1. Use HTTP Basic Authentication

There are many ways to deal with authentication in REST API but the simplest way to deal with the authentication is HTTP basic authentication.

A common use of basic authentication is for identification purpose- The user needs to provide a username and password as a means of identification, for using statistic data from the server.

If a request does not include an appropriate Authorization header, the API sends a 401 Authorization Required as a result:

2

Request is issued when a particular credential is used:

4

This table shows the process for encoding credentials in base64.

2

2. Use Custom Content Type

If you are using standard text/xml content-type then you need to stop because it is very vague and user finds difficult to understand.

Instead of these standard text/xml use custom content type in the following form:

5

This allows your clients to process the information as the specified content-type. All three of these content-types are categories, but they are represented in different formats (xml, html, and json).

But before using this custom content type the client need to know in advance, what to expect because they can’t ask any specific information which is outside the knowledge like the URL etc.

3. Respond with standard media types

If you are using Custom media type, then it is recommended that the service returns a response using a content type header with standard “application /json” or application/xml media type and an additional custom type header such as shown below:

X-hedtech-Media-Type: application/vnd.hedtech.v4+json

Responding with standard application/json is useful for client learning about your API, as browser add-ons will enable clients to make easily view the response.

An API may always respond with a custom header, even when identifying a standard media type. That is, a custom header may be used even if it identifies the same standard media type identified in the Content-Type header.

4. Use Link Type Relations

Using link is a perfect way to signal what type of resource is being used or linked to.

For example, a custom rel for a user resource might be http://rel.myapi.com/user, which serves two purposes:

  • Clients of your API must know this key ahead of time, as it is API-specific knowledge. For example, if it was available on your initial resource and you were using HAL to link to the user resource, clients might find the user link via initialResource._links[“http://rel.myapi.com/user”].href.
  • Developers writing API clients can visit that URI in their web browser, and get an explanation of what that resource represents in your API, including what methods are applicable and what they do.

If you are using link type relation than it is important that we should make sure that they behave as expected, otherwise they might confuse our client.

5. Use cURL

cURL is a command line tool for transferring data across various protocols, including HTTP and support a various platform like Linux, Windows, Mac OS and Solaris.

Most Linux distribution includes cURL in their package.

cURL uses command line interface to send a request to an HTTP server and the request includes this command line syntax.

6

Here the uri refer to the target HTTP address to send the request.

There is four type of option available in cURL:

1. -X COMMAND, –request COMMAND

In the context of the REST API, you can use this request command with GET, POST, PUT or DELETE.

Example: -X GET

2. -H LINE, –header LINE

Use header line option when you required more than one header.

Example: -H “Accept: application/xml” -H “Content-Type: application/xml”

3. -u USERNAME:PASSWORD, –user USERNAME:PASSWORD

This username and password act as a convenient replacement for the Authorization header.

Example: -u admin@internal:p@55w0rd!

4. –cacert CERTIFICATE

In a context of REST API it use to find the location for SSL communication. The certificate file is saved locally on the client machine. Use the -k attribute to bypass SSL.

Example: –cacert ~/Certificates/rhevm.cer

5. -d BODY, –data BODY

In context for REST API, a body is used to request. Use POST, PUT, and DELETE requests with this body request and ensure to specify the Content-Type: application/xml header if a body exists in the request.

Example: -d “<cdrom><file id=’rhel-server-6.0-x86_64-dvd.iso’/></cdrom>”

Let us go through some example and see how to adapt REST requests to cURL command syntax:

Example 1. GET Request

The following GET request lists the virtual machines in the vms collection. Note that a GET request does not contain a body.

7

Now adapt the GET request method, header (Accept: application/xml) and URI (https://[RHEVM-Host]:8443/api/vms) into the following cURL command:

8

An xml representation of  vms collection display.

Example 2. POST Request

The post request creates a virtual collection in vms collection. but keep in mind that POST request requires a body.

9

Adapt POST request method, headers (Accept: application/xml and Content-type: application/xml), URI (https://[RHEVM-Host]:8443/api/vms) and request body into the following cURL command:

10

The REST API creates a new virtual machine and displays an XML representation of the resource.

Example 3. PUT Request

PUT request update the memory of virtual machine resources. It also requires body.

11

Adapt PUT request method, headers (Accept: application/xml and Content-type: application/xml), URI (https://[RHEVM-Host]:8443/api/vms/082c794b-771f-452f-83c9-b2b5a19c0399) and request body into the following cURL command:

12

These requests update the virtual machine with new memory configuration.

Example 4. DELETE Request.

These requests remove virtual machine resources.

13

Adapt the method (DELETE) and URI (https://[RHEVM Host]:8443/api/vms/082c794b-771f-452f-83c9-b2b5a19c0399) into the following cUrl command:

14

The REST API removes the virtual machine. Note the Accept: application/xml request header is optional due to the empty result of DELETE requests.

6.  Use 4xx and 5xx status code

The status code is defined as the data section of the message error, Forward and redirection responses may be used to contain human-readable diagnostic information.

The 4xx  status code is used to tell the client that the fault has been taken on their side. This status code contains the explanation of the error situation, whether it’s temporary or permanent condition.

These status codes are applicable to any request method.

Decision chart of the 4xx status code

15

 

 

5xx codes tell the client something happened on the server and their request by itself was perfectly valid. Except when responding to this error the server should contain the information of the error situation, whether it’s temporary or permanent condition.

These response codes are applicable to any request method.

Decision chart of the 5xx status code

16

7. How to delete a resource

The API delete a resource by using DELETE Request which is send to URI.

17

Some cases require optional body content in the DELETE request to specify additional properties.

A Delete  Request with an optional body may look like this:

Content-Type: application/xml header to inform the API of the XML representation in the body content.

If a DELETE request contains no body content, omit the Content-Type: application/xml header.

8. Use a Consistent Representation ‘Domain Style’

A consistent representation ‘Domain Style’ are used to represent appropriate attribute, element names, and structure which include hierarchical structures too.

Mike Amundsen identifies three primary styles for representing domains: ‘domain-specific’, ‘general’, and ‘agnostic’.

Domain    Style                                           Description
domain-specific    Closely models the domain with respect to element names and          structure. Example element: “home-address”
general    General element names are used whenever possible (and these          are then decorated with attributes to provide the specificity).            Example element: “address”: {“type”:”home }
agnostic    Uses generic element names and relies on attributes to provide        context. Example element: “ul”: {“type”:”home-address” }

 

These Domain style strategies provide following  guidance:

  1. Recognize these styles and apply them consciously
  2. Favor use of the ‘domain-specific’ style due to its simplicity
  3. Collaborate with GA to determine if there are reusable representations that may be used.
  4. Balance “purity” with pragmatism. Authors and standards like OData specify affordances that some may not consider pragmatic. It is recommended to balance the ‘purity’ of approach with simplicity and productivity.

 

9. Use HTTP  PATCH method

HTTP PATCH method are used to apply the partial modification to resources. The PATCH method requests a set of changes described in the request entity be applied to the resource identified by the Request-URI.

This set of change is represented in a format called “PATCH document” which is identified by the media type.

If the Request-URI does not point to an existing resource, the server MAY create a new resource, depending on the patch document type (whether it can logically modify a null resource) and permissions, etc.

PATCH Example:

PATCH /file.txt HTTP/1.1

Host: www.example.com

Content-Type: application/example

If-Match: “e0023aa4e”

Content-Length: 100

10.  Use Automated Testing

Every modern platform supports these best practice and it is one of the best practice which cannot be avoided. It is an absolute requirement for RESTful APIs.

Automated testing is used to test all representation of resources and also expected responses both success and error.

Support for testing RESTful endpoints is often built-in to a testing framework or supported through a third party library. When available, higher-level abstractions (i.e., DSLs) should be used. For example, the following Groovy snippet shows the use of a higher-level DSL supporting REST:

post(“/api/colleges”) {   // ‘POST’ /api/colleges => ‘create’

headers[ ‘Content-Type’ ] = ‘application/json’

headers[ ‘Authorization’ ] = authHeader()

body { “””

{

“description”: “Great Valley University”,

“code”: “GV”,

“systemRequiredIndicator”: “Y”,

}

“””

}

}

assertStatus 201

assertEquals ‘application/json’, page?.webResponse?.contentType

def stringContent = page?.webResponse?.contentAsString

def data = JSON.parse( stringContent ).data

 

id = data.id

assertNotNull “Expected new College with an id but got: ${data}”, id

assertEquals “Expected code ‘Z9’ but got ${data.code}”, ‘Z9’, data.code

11. How to report a validation Error.

If you are using a ‘400’ status code for validation error then it is recommended that your Custom HTTP header must have some additional information like:

X-Status-Reason: Validation failed

Validation errors should also be provided within the response body.

The JSON or XML should provide details of any validation errors if a 400 or 422 status code is returned. Following is an example error:

{ “errors” : [

{

“type”: “validation”,

“resource”: {

“id”: 25

},

“message”: “districtDivision value exceeds two character limit”

}

]

}

The specific structure and format of detailed error information is not standardized, and this strategy allows for different representations since various frameworks handle such responses differently.

 

 

The post Guide to Rest API Best Practices V.2 appeared first on  - Snyxius.


Viewing all articles
Browse latest Browse all 167

Trending Articles