Showing posts with label rest api. Show all posts
Showing posts with label rest api. Show all posts

Tuesday, August 3, 2021

Top 7 REST API Best Practices

 

REST API, an acronym for representational state transfer. It is an architectural style for distributed hypermedia systems. It is a flexible method of designing APIs in a way that follows certain protocol. A REST API lets client to communicate with the server by transferring states of data stored primarily in a database. As clients and servers work independently, you need some interface that can work with correspondence between them. A client sends a request to the server through the API, which returns the response in a standardized format such as JSON or XML. REST APIs play an important role in easing the communication in servers, hence it is important for developer to have a deep understanding of how to use them. Error-prone API causes functional issues for client and makes the software less appealing altogether.

Here we’ll see the best practices for designing REST APIs to ensure the best performance. But before digging into it let’s see 6 RESTful Architectural Constraints

6 REST Architectural Constraints-

1. Uniform Interface-

By REST, you use a similar concept to decouple the client from implementing the REST service. Compare interface with contract signed between client-server where you must use specific standards. Globally accepted APIs should uphold global concepts, like standards, to make them understandable.

2. Client-Server-

Here, the meaning is that server application and client application should evolve individually without need to depend on each other. To be more exact, it should adhere to the separation of concerns. By separation of concerns, the code on the client end can be modified without making any effect on the conditions of the worker. Also, code on server end can be modified without changing the conditions of client. You can improve the flexibility and scalability of particular interface across various platforms by maintaining separation of concerns. Client should be aware of resource URIs only. Till the interface between client and servers is kept unaltered, they can be developers and replaced separately. 

3. Layered System-

Mostly, components cannot view beyond the immediate layer. REST enables you to make use of a layered architectural system. Here, you can deploy APIs on server A, save data on server B, and verify requests on server C. These servers might offer a security layer, a load balancing layer, a caching layer and some other functionalities. Also, any of these layers must not influence the response or requests.

4. Code On Demand –

Generally, it is an optional constraints. Mostly you will need to send a static representation of resources in a JSON REST API or XML form. But, when you need to, you can easily return executable code for supporting important part of your app.

5. Stateless-

By this architectural constraints, you mean to make al the client-server engagements stateless. In this way, server won’t reserve anything about the latest HTTP request made by client. So it’ll consider each request as a new and unique. Also, it must not depend on any prior information exchanged between the two. It means no session, no history. Client is held accountable to handle the app’s state. Client app needs a stateful app for end-user, where the logs in once and carries out different authorized operations. Each request from client must involve all necessary information to serve the request and authorization details and authentication.

6. Cacheable-

Caching holds importance wherever applicable. It improved the performance for the client, that leads to an improved scope for scalability for a server with reduced load. In case of REST, each response can be termed as cacheable and non-cacheable. One can use the cached response as the request-response rather than checking with the server. It helps to reduce the interaction between server and client.

Top 7 REST API Best Practices-

1. Use JSON To Send And Receive Data-

Well-designed REST API should always accept and receive data in JSON format. JSON is lightweight data exchange format standard for developers. This is available in lots of technologies and makes encoding and decoding easy and fast on server side because of its lightweight nature. Also, JSON is readable and simple to interpret. XML, is not supported by many frameworks. Also, XML data manipulation can be issue compared to JSON because it is a verbose and difficult to write. To ensure that REST API is using JSON format, set the Content-Type in the response header to application/JSON. Lots of backend frameworks have built-in functions to automatically parse the data to JSON format.

2. Use Noun Rather Than Verbs-

API development REST approach can be called resource based. Hence in your app, you work with resources and their collections. Actions on resources are defined by HTTP methods like GET, PUT, POST, PATCH, DELETE and only they should be used to change the state of response. It leads to endpoint URI construction. Considering all this, constructed endpoint should look like-

GET /books/123
DELETE /books/123
POST /books
PUT /books/123
PATCH /books/123

You can employ Express to implement these endpoints to manipulate articles like,

const express = require(‘express’);
const bodyParser = require(‘body - parser’);
 
const app = express();
 
app.use(bodyParser.json());
 
app.get(‘/articles’,(req, res) => {
const articles = [];
 // code to retrieve an article..
res.json(articles);
});
 
app.post(‘/articles’, (req, res) => (
 // code to add a new article…
 res.json(req.body);
});
 
app.put(‘/articles/:id’, (req, res) => {
Const { id } = req.params;
//code to update an article…
res.json(req.body);
});
 
app.delete(‘/articles/:id’, (req, res) => {
Const { id } = req.params;
//code to delete an article…
res.json({deleted: id });
});
 
app.listen(3000, () => console.log(‘server started’));

3. Use Plural Naming Conventions-

Generally we prefer the use of plurals. But there is no rule that states one cannot use a singular when it comes to the resource name.Then why use plurals.

We work on one resource from the set of resources. Thus, to illustrate collection, we use plural naming conventions.

For instance, let us consider GET/users/123. Here client asks to rectify and recover a resource from user’s collection with ID 123. While developing a resource, if we need/wish to add another resource to the existing collection of resources, the API looks like POST /users.

4. Allow Filtering, Sorting, And Pagination-

Some features for consuming API include filtering, sorting and paging. Mostly resource collection can be huge. Databases behind REST API standards can get enormous. It brings down the performance of systems. To eradicate this, one can use,

  • Sorting- It enables sorting that results in an ascending or descending order by selected parameter/(s) like date
  • Paging- It uses ‘limit’ to narrow down the count of results displayed to specific number and ‘offset’ to denote the part of result range to be displayed. This is important where the count of total outcomes is greater than introduced. 
  • Filtering- Use to shrink the query results by specific parameters like country 

By pagination data, you ensure returning only some of the results rather than collecting all the necessary data at once. By filtering and pagination, one can improve the performance as there is a potential reduction in the use of server resources. With more data assembling in the database, these features become important.

5. Error Handling-

To reduce the confusion for all API users, it is necessary to handle errors perfectly, in that way returning the HTTP response codes that denote nature of error that has occurred. It provides API maintainers sufficient information to analyze the source and cause of problem. If you don’t want to harm your system, you can leave it unhandled. All this means that API consumer has to handle errors. Let’s have a look at a list of common error HTTP status codes.

  • 404 Not Found- This denotes that no resources are found.
  • 401 Unauthorized- It denotes that the user is unauthorized to access a resource. Generally it returns when a user is not verified.
  • 400 Bad Requests- It denotes that the client-side input has failed documentation/validation.
  • 403 Forbidden- It states that the user is inappropriate and is not allowed to access a resource even after being verified.
  • 502 Bad Gateway- This error marks an invalid/null response from an upstream server.
  • 503 Service Unavailable- It denotes that something unusual activity took place on the server-side.

Error codes are necessary to accompany messages with them so that API maintainers can get appropriate data for troubleshooting the issue. But attackers can’t use error content for cyberattacks like bringing the system down or stealing important data. If API stays incomplete, you should send errors with information to allow users to take appropriate actions.

6. Resource Hierarchy-

If resource includes sub-resources, ensure depicting this in API, so making it clear and specific. For example, if user has posts and you want to retrieve a specific post by the user, API can be interpreted as GET/users/123/posts/1. It will retrieve the post with id one by the user having id 123. Most of the time, resource objects can be linked with another or possess some kind of functional hierarchy. Usually it is better to restrict the nesting to a single level in REST API. 

7. Idempotence (Misusing Safe methods)-

Some safe methods are HTTP methods that return the exact resource representation. TRACE, GET, OPTIONS and HEAD methods are referred to safe. Meaning that, they are ideally expected to retrieve data without changing the state of resources on the server. Besides, refrain from using GET to delete content, like GET/user/123/delete. Basically, it is not like, it cannot be executed, but the issue arises because in this case HTTP specification gets violated. So use HTTP methods according to the action that you need to carry out.

Wrap Up-

APIs has the capacity to turn any service easy or extremely complicated. The best way to design a high-quality REST API standards is maintaining consistency by sticking to conventions and web standards. In the modern web, JSON, HTTP, SSL/TLS status codes are some standards building blocks. To improve performance, ensure that you don’t return lots of data simultaneously.  With caching, you don’t need to query for data every time. Also, maintain consistency in the path of endpoints. 

If you are thinking of building a software consult with Solace experts. We are here to help you through consultation and development. You can hire dedicated developers of the Solace team for effective software development. Connect with Solace and get a free quote for best software development. We will be happy to help you.

Thursday, September 19, 2019

SOAP vs REST: A Comparison of Two Different API Styles

When you are thinking about API (Application programming interface) architectures, it is common to compare SOAP vs REST. Both are the most common API paradigms. In spite of the fact that the two are quite similar but they are different technologies and are not compared on a granular level. The question is, Why? Because SOAP is a protocol and REST is an architectural style. A REST API can use the SOAP protocol, similar to that it can use HTTP. So, they will be bundled differently, function differently and be used in different scenarios. Let us see, SOAP and REST one by one.

What Is An API?

An API is a part of software that plugs one application directly into the data and services of another by granting it access to specific parts of a server. APIs allows two parts of software to communicate. They’re the reason for everything we do on mobile, and also allow us to streamline IT architectures, power savvier marketing efforts, and make easier to share data sets. Similar to other software, API’s can be pretty straightforward and also there different ways to program one with different attributes that are better for your application. Also, with more built-in features comes more overhead—something we’ll see when we look at what SOAP has to offer.

What Is SOAP?

SOAP (Simple Object Access Protocol) is its own protocol. It is a more complex by defining more standards than REST things like security and how messages are sent. These built-in standards do carry a bit more overhead, but can be a deciding factor for organizations that require more comprehensive features in the way of security, transactions, and ACID (Atomicity, Consistency, Isolation, Durability) compliance. For this comparison, we should bring up that a significant number of the reasons SOAP is a decent decision once in a while applying to web services scenarios, which makes it increasingly perfect for big business type circumstances. Reasons you might need to build an application with a SOAP API incorporate more elevated amounts of security (e.g., a mobile application interfacing with a bank), informing applications that need solid correspondence, or ACID consistency.
  • SOAP has tighter security- WS- Security, in addition to SSL support, is a built-in standard that gives SOAP some more enterprise- level security features, if you have a requirement for them.
  • Successful/ retry logic for reliable messaging functionality- REST doesn’t have a standard informing framework and can just address correspondence disappointments by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
  • SOAP has built-in ACID compliance- ACID compliance reduces anomalies and secures the integrity of a database by recommending exactly how transactions can interact with the database. ACID is more conservative than other data consistency models. Hence it is favored for handling financial or otherwise sensitive transactions.

What Is A REST API?

REST (Representational State Transfer) is a “web services” API. These are based on URIs (Uniform Resource Identifier) and the HTTP protocol. It uses JSON for a data format, which is super browser-compatible. REST APIs can be simple to build and scale, but they can also be massive and complicated. Reasons you may want to build an API to be RESTful include resource limitations, fewer security requirements, browser client compatibility, discoverability, data health, and scalability things that really apply to web services.
Some quick REST information:
  • REST is simple because of HTTP protocols.
  • REST APIs encourage customer server communication and models. If it’s RESTful, it’s built on this client-server principle, with round trips between the two passing payloads of information.
  • REST APIs use a single uniform interface. 
  • This API is optimized for the web. 
  • For excellent performance and scalability, REST is popular. 

SOAP vs REST-

  • SOAP is a protocol. REST is an architectural style.
  • REST APIs access a resource for data (a URI); SOAP APIs perform an operation. REST is an architecture that’s more data-driven; SOAP is a standardized protocol for transferring structured information.
  • REST grants various data formats, including plain text, HTML, XML, and JSON, which is an extraordinary fit for information and yields more browser compatibility; SOAP only uses XML.
  • Security is handled differently- SOAP supports WS-Security. It is great at the transport level and more comprehensive than SSL, and more ideal for integration with enterprise-level security tools. Both support SSL for end-to-end security, and REST can use the secure version of the HTTP protocol, HTTPS.
  • SOAP requires more bandwidth; REST requires fewer resources 
  • REST calls can be cached, SOAP-based calls cannot be cached. 
  • An API is built to handle your app’s payload, and REST and SOAP do this differently. 

When to use REST and when to use SOAP?

Most debating topic is when to use REST and when to use SOAP. Here are some key factors to determine when each technology should be used for web services.

REST should be used in the following instances –

  • Limited resources and bandwidth– SOAP messages are heavy content messages and consume a far greater bandwidth. REST should be used in instances where network bandwidth is an imperative.
  • Statelessness – In case of no need to maintain a state of information from one request to another, REST should be used. On the off chance that you need an appropriate data flow  wherein, some data from one request needs to flow into another then SOAP is more suited for that case. 
  • Caching – If there is a need to cache a lot of requests then REST is the perfect solution. At times, clients could request for the same resource multiple times. This can increase the number of requests which are sent to the server. 
  • Ease of coding- Coding REST Services and subsequent implementation is simpler than SOAP. So if a quick perfect solution is required for web services, then REST is a better option to choose.

SOAP should be used in the following instances-

  1. Asynchronous processing and subsequent invocation – If there is a requirement that the client needs a guaranteed level of reliability and security then you can use new SOAP. 
  2. A Formal means of communication– If both the client and server have an agreement on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  3. Stateful operations – If the application has a necessity of maintaining state data, from one request to another, then the SOAP 1.2 standard provides the WS* structure to support such requirements.
Are you thinking to develop a software to boost up your business? Then you are at the right place. Solace expert’s are well trained to use Node.js REST APIs and SOAP practices for effective development. To get a free quote for any software/web development, contact us. We are happy to help you get started through our expert’s.

Wednesday, August 7, 2019

Top 10 Practices for Writing Node.js REST APIs from Node Gurus


Here we will see the best practices for writing Node.js REST APIs. This includes topics such as authentication, naming your routes, black – box testing and also using proper cache headers for these resources. One of the most popular use-cases for Node.js is to write RESTful APIs using it. Let us see practices for writing Node.js REST APIs. 

Best practices for Writing Node.js REST APIs from Node Gurus-

1 – Use HTTP Methods & API Routes-

You can build a Node.js RESTful API for creating, updating, retrieving or deleting users. For these operations, HTTP has toolset:  POST, PUT, GET, PATCH or DELETE.
As a best practice, your API routes should always use nouns as resource identifiers. The routing can be look like: 
  • POST /user or PUT /user:/id to create a new user
  • GET /user to retrieve a list of users
  • GET /user/:id to retrieve a user
  • PATCH /user/:id to modify an existing user record
  • DELETE /user/:id to remove a user.

2. Use HTTP Status Codes Correctly-

If something wrong with serving a request, you must set the correct status code in the response: 
  • 2xx, if everything was okay,
  • 3xx, if the resource was moved,
  • 4xx, if the request cannot be fulfilled because of a client error (like requesting a resource that does not exist),
  • 5xx, if something went wrong on the API side (like an exception happened).
If you are using Express, setting the status code is as easy as res.status(500).send({error: ‘Internal server error happened’}). Similarly with Restify: res.status(201).

3. Choose the right framework for your Node.js REST API-

It is necessary to choose the right framework. 
  • Express, Koa or Hapi- These three are used to create browser applications. They support tempting and also rendering to name a few features. If application needs to provide user-facing side also, it helps for this. 
  • Restify- Restify is focuses to help you for building REST services. It lets you build “strict” API services that can be maintained and observed. Restify also come with automatic DTrace support for all your handlers. For the production of major applications like npm or Netflix, it is useful.

4. Use HTTP headers to send metadata- 

To connect metadata about the payload you are going to send, use HTTP headers. 
  • pagination
  • rate limiting
  • or authentication
If you require to set any custom metadata in your headers, it will be good to prefix them with x. For eg., if you are using CSRF tokens, it is a general way to name them x-Csrf-Token. Anyway with RFC 6648 they got deprecated. New APIs should try to not utilize header names that can strife with different applications. For eg., OpenStack prefixes its headers with OpenStack. 
OpenStack-Identity-Account-ID
OpenStack-Networking-Host-Name
OpenStack-Object-Storage-Policy
Make clear, that the HTTP standard does not define any size limit on the headers. However, Node.js (as of writing this article) imposes an 80KB size limit on the headers object for practical reasons.

5. Black-Box Test your Node.js REST APIs-

It will be the best way to test REST API by treating them as a black box. Black box testing is a testing method where the functionality of an application is analyzed without knowing its internal structure and also working. So none of the dependencies are mocked or stubbed, but the system is tested as a whole. Supertest module can help you with black-box testing Node.js REST API. 
A simple test case that checks if a user is returned using the test runner mocha can be implemented like this: 
const request = require(‘supertest’)
describe(‘GET /user/:id’, function() {
  it(‘returns a user’, function() {
    // newer mocha versions accepts promises as well
    return request(app)
      .get(‘/user’)
      .set(‘Accept’, ‘application/json’)
      .expect(200, {
        id: ‘1’,
        name: ‘John Math’
      }, done)
  })
})
As per your needs, you can populate database with test data with either of the following ways: 
  • Run your black-box test scenarios on a known subset of production data,
  • Populate the database with crafted data before the test cases are run.

6. Do JWT-Based, Stateless Authentication-

As your REST APIs must be stateless, so does your authentication layer. For this, JWT (JSON Web Token) is ideal.
It consists of 3 parts:
  • Header, containing the type of the token and the hashing algorithm
  • Payload, containing the claims
  • Signature (JWT does not encrypt the payload, just signs it!)
Adding JWT-based authentication to your application is like-
const koa = require(‘koa’)
const jwt = require(‘koa-jwt’)
const app = koa()
app.use(jwt({ 
  secret: ‘very-secret’ 
}))
// Protected middleware
app.use(function *(){
  // content of the token will be available on this.state.user
  this.body = {
    secret: ’42’
  }
})
JWT module does not depend on any database layer. Because all JWT tokens can be verified on their own, and they can also contain time to live values.

7. Conditional requests- 

Conditional requests are nothing but the HTTP requests which are executed differently depending on specific HTTP headers. If these requests are met, the requests can be executed in different ways.
These headers attempt to check whether a version of a resource stored on the server matches a given version of the same resource. Hence these headers can be:
  • the timestamp of the last modification,
  • or an entity tag, which differs for each version.
These headers are:
  • Last-Modified (to indicate when the resource was last modified),
  • Etag (to indicate the entity tag),
  • If-Modified-Since (used with the Last-Modified header),
  • If-None-Match (used with the Etag header),

8. Embrace Rate Limiting-

This is used to control how many requests a given consumer can send to the API.
Set the following headers, to tell your API users how many requests they have left:
  • X-Rate-Limit-Limit, the number of requests allowed in a given time interval
  • X-Rate-Limit-Remaining, the number of requests remaining in the same interval,
  • X-Rate-Limit-Reset, the time when the rate limit will be reset.

9. Create a Proper API Documentation-

You write APIs so that others can use them and also take benefit from them. Providing an API documentation for your Node.js REST APIs are crucial.
Below open-source projects can help you with creating documentation for your APIs:
  • API Blueprint
  • Swagger

10.Don’t Miss The Future of APIs-

In the previous years, two major query languages for APIs emerged – namely GraphQL from Facebook and Falcor from Netflix. Why these are necessary?
Imagine the following RESTful resource request:
/org/1/space/2/docs/1/collaborators?include=email&page=1&limit=10
This can get out of hand quite easily – as you’d like to get the same response format for all your models all the time. This is where GraphQL and Falcor can help.
Don’t know how to write Node.js REST APIs? Contact us for free consultation and any query regarding Node.js REST APIs. We at Solace are here to help you with our expert’s team.