Duplicate Transaction
How to design an API

How to design an API

In my last three articles, I discussed APIs, JSON, and REST.
In this article, I am going to show you how to design an API with best practices.

Define and Design

The first step in building an API is to define what it’s that you want to build, decided the API architectural style, and form an API style guide.

After you defined your application’s domain, you can start by defining your resources. A resource could be any object that we can request information about it from the API.

What are the resources exposed in your API?

For example, a basic payment service may feature the following resources: 

  • users 
  • Transactions 

We have to consider the possibility of one of our resources to be the parent of another; for example, one user may have multiple transactions.

Next, we need to identify a field or fields for each resource.

In our example, the Transaction resource may have the following fields:

  • Name
  • Amount
  • Card Type
  • Last four digits of the card number
  • Cardholder
  • Date

Make sure to always add a field for the resource name. 

//example.com/users/1
//example.com/users/1/transactions/1

The Users in the first example is the collection Id, and 1 identifies the resource Id.
The first sample is a user identified by the Id number of 1. The second example is a transaction Id of 1 associated with user 1.

//example.com/users/

The above example identifies all users.

Since we are designing a RESTful API, resource names become the HTTP endpoints.

//example.com/users/1/transactions

We have to break down the domain terms, create their data models, and mark these models as resources when needed.
The following is an example of a data model for a credit card transaction:

class transaction
    {
        public  $TransactionResult;    
        public  $ResponseCode;               
        public  $ApprovedAmount = 0;    
        public  $TransactionID;
        public  $AuthCode;    
        public  $CardType;
        public  $AccountNum;
        public  $ExpDate;
        public  $TicketID;
        public  $ResponseMsg;
        public  $HostCode;
        public  $Timestamp;
        public  $CardHolder;
        public  $BusinessId;
        public  $UniqueId;
        public  $TransType;
}

From this data model, we make our transaction resource.

Methods

A Method is a specific operation that a client performs on a resource. Most APIs provide the following operation resources:

 LIST, GET, CREATE, UPDATE, and DELETE

These operations are also known as standard methods. 

You can include custom methods in your API service, but only when none of the standard methods can describe your purpose adequately.

Methods are always associated with resources, whether one single resource or a list of them. Our credit card payment service, for example, could provide the following methods:

CREATE (Creates a transaction)

/example.com/transactions/ (a collection of Transaction resources)

GET (Gets a transaction)

//example.com/transactions/trasnactionId (a single Transaction resource)

UPDATE (Updates a transaction)

//example.com/transactions/trasnactionId (a single Transaction resource)

LIST (Lists transactions by a user)

//example.com/transactions/transactionId/user (a collection of User resources)

DELETE (Deletes a transaction)

//example.com/transactions/transactionId/users/userId (a single User resource)

In HTTP RESTful APIs, we map each method to an HTTP verb (see this article). Invoke a method by sending a corresponding HTTP verb, to an HTTP URL path (endpoint).

Common Patterns

As a matter of good practice, always consider creating the following patterns:

1- Collections (Batch processing)

Consider a request when the client asks for a list of transactions for a specific date range.

In your design, you have a GET operation to fetch a transaction record. A collection allows the client to request all qualified transactions in one request, instead of running multiple single GET operations.

 In HTTP RESTful APIs, batching improves the performance of your system.

2- Pagination

When your API returns a collection of records, you need to provide a pagination method, so the data can browsed page by page, instead of a long single page format.

3- Beware of Idempotency

Those HTTP methods that do not change the resource are known as Safe methods. GET, for example, is a safe method. 

It does not matter how many times your request a GET, you always receive the data record, without any changes.

GET is an Idempotent method (incapable).

Let’s look at CREATE. This method creates a new record of your resource. If a client requests this method multiple times, the result would be unwanted new records of your resource.

When a method is not safe, and each request results in creating new records, updating records or deleting records, it is not idempotent.

Consider the following examples:

a = 7;
a++;

The first statement always returns the value of 4 for the variable “a.”
The second statement, in each call, adds 1 to the current value of the variable “a” and returns its results.
After 3 calls, the first statement returns 4, and the second statement returns 7.
The first statement represents an idempotent method, and the second one is a non-idempotent.
So, when you design your API, make sure to place safeguards in your code to prevent unwanted effects of non-idempotent methods. You don’t want to create duplicate records, or delete records accidentally!

HTTP MethodIdempotentSafe
OPTIONSYESYES
GETYESYES
HEADYESYES
PUTYESNO
POSTNONO
DELETEYESNO
PATCHNONO
HTTP Methods and idempotency

4- Error Handling

You cannot ignore errors, and you cannot prevent them all the time.

Manage errors and let your API to handle the errors elegantly, instead of a crash!

If API cannot serve a request, it should return a clear, specific, and helpful message. Always include an error code (machine-readable), an error message (human-readable), and don’t hesitate to provide additional contexts that could help the developers to alleviate the problem.

In HTTP RESTful APIs, always use HTTP status codes for error codes.

Formalize your Style Guide

Write down the conventions in a clear and concise form. The Style Guide defines the conventions of your API—such as the media type you’re going to use, the kind of authentication you put in place, error messages and error codes, or the way you paginate results. It also covers the naming conventions, URI formatting. Think of it as a coding style guide for your API.

Everything should be ready for you to move to the next step, which is to develop your API. You need a server before getting to the nitty-gritty of the development and writing of actual code.

Your API is going to be accessed 24/7, and perhaps by a vast number of clients, you need to select a reliable, accessible, and fast platform for your server.

I have always recommended Amazon Web Services, but you can go any service you like and perhaps familiar.

At last, the moment we all love–writing the code!

It is entirely up to you as to what programming language, framework, or platform you are going to use to implement your API. 

Happy Coding!

Kourosh

Your Header Sidebar area is currently empty. Hurry up and add some widgets.