• Creative Corner
  • Tips
  • Blog
14 March, 2017

Best Practices for Designing Restful APIs

9series | 0Comment(s)

Best-Practices-for-Designing-Restful-APIs

 

A deliberately designed RESTful API describes relationships, schema, resources and structure which will be easily available by the native apps.

When you develop & deploy any web API, consider requirements for the physical environment to host APIs and the way it’s developed rather than the logical structure.

API serves functionality of an application for other clients to use. With the use of API, applications interact with each other and yield output without any user knowledge.

Generally, web applications should have RESTful JSON APIs. REST stands for “Representational State Transfer” a fundamental style and approach to communications and used to develop scalable web services. JSON is lightweight and is in a readable format and it is used to structure the data.

API_arch

Here are some pragmatic best practices to build a RESTful APIs using ASP.NET.

Use HTTP methods:

  • Use URLs to specify resources and HTTP methods to specify what to do with this resources.
  • Read: Use GET to retrieve relevant resources. The GET method has a read-only semantic and can catch calls perfectly.
  • Create: Use POST to create new resources.
  • Update: Use PUT to update existing resources.
  • Delete: Use DELETE to delete existing resources.

Use HTTP status code to handle errors:

API should give response with suitable status code and appropriate message in the response body.

There are many HTTP status codes, some are listed here:

200 OK – [GET]
201 CREATED – [POST/PUT/PATCH]
204 NO CONTENT – [DELETE]
304 NOT MODIFIED
400 INVALID REQUEST – [POST/PUT/PATCH]
401 UNAUTHORIZED
403 FORBIDDEN
404 NOT FOUND
500 INTERNAL SERVER ERROR

Here is an example for some HTTP methods & status code to use to perform CRUD operation using APIs

HTTP Verb CRUD Entire Collection (e.g. /customers) Specific Item (e.g. /customers/{id})
POST Create 201 (Created) 404 (Not Found),
GET Read 200 (OK) 200 (OK)
PUT Update/Replace 404 (Not Found) 200 (OK) or 204 (No Content). 404 (Not Found)
PATCH Update/Modify 404 (Not Found) 200 (OK) or 204 (No Content). 404 (Not Found)
DELETE Delete 404 (Not Found) 200 (OK). 404 (Not Found)

HTTP method Overriding:

Some proxies don’t support PUT or DELETE. This is because of browser or really tense corporate firewall. So to overcome these limitations, API needs a way to override HTTP method and we can call it “tunnel” also. So that means a header says “Seriously!!..I got here via POST, but I will allow you to use this one instead.” To achieve this functionality, use “X-HTTP-Method-Override: PUT” as a header.

Simplify Associations:

Data / Resources always have relationships with other resources. We’re using HTTP verbs to operate on the resources and collections. For example, city belongs to country. To get all the cities of specific country, or to create new city for that country, use GET or POST method. Representation of these associations in URL are like: “GET country/21/city”. This URL will return all cities of specific country and using “POST country/21/city” It will create city and relationships between specific country.

Use the Query String (?) for Optional or Complex Parameter:

Always keep URL short and simple. Select one base URL for resource and move complexity or optional parameters to query string.
EG. “GET /students/standard=12&subject=physics”

Filtering, Sorting and Paging for Collections:

Use a unique query parameter for all fields or a query language for filtering.

  • Filtering: GET /students?class=12 will return students of class 12th.
    GET /students?marks
  • Sorting: Allow ascending and descending sorting over multiple fields.
    GET /students?medium=English
  • Paging: Use limit and offset. It is flexible for the user and common in leading databases. To send the total entries back to the user, use custom HTTP header : X-Total-Count links to the previous or next page should be provided in the HTTP header link as well.
  • API Versioning: Make the API version mandatory and do not release an unversioned API and avoid dot notation such as 2.5.
    Versioning API will help to emphasize rapid and invalid block requests from hitting updated endpoints. It will likewise help smoothly over any major API version transitions to continue old API versions for a time being.
    There are lot of mixed opinions regarding API version that it should be managed through URL or in a header; Academically speaking, it should be in a header. However, the version needs to be in the URL to ensure browser exploration of the resources across versions.
    The URL has a significant version number (v1), but the API has date based sub-versions which can be determined using a custom HTTP request header. In this case, the significant version provides structural stability of the API as a whole, while the sub-version accounts for smaller changes (field deprecations, endpoint changes, etc).

Documenting your REST API:

As a developer, make use of API documentation to understand how to utilize a service on which we are depending on. Getting started from the scratch is always the biggest challenge and time consuming, so I greatly appreciate those APIs that are very well-documented. Some of them even make it fun to learn to make effective and easy understandable document.

Below are the points that are good to have in your document.

  • Title: Additional information about your API. Try to use verbs.
  • URL: The URL Structure (path only, no root url)
  • Method: The request type
  • URL Params: If URL params exist, specify them in accordance with name mentioned in URL section. Separate the section into Optional and Required.Required:
    id=[integer]
    Optional:
    photo_id=[alphanumeric]
  • Data Params: If the request type is POST, what should be the body payload look like? URL Params rules apply here too.
  • Success Response: What should be the status code and is there any return data? This is useful when people need to know what their callbacks should expect! Code: 200
    Content: { id : 12 }
  • Error Response: Most endpoints have many ways to fail. From unauthorized access, to wrongful parameters etc. All of those should be listed here. It might seem repetitive, but it helps prevent assumptions from being made. Code: 401 UNAUTHORIZED
    Content: { error : "Log in" }
  • Sample Call: A sample call to your endpoint in a runnable format ($.ajax call or a curl request) – this makes life easier and more predictable.

Example:

  • City: Returns JSON data about a city.
  • URL: City/Cid
  • Method:GET
  • URL Params Required:Cid=[integer]
  • Data Params:None
  • Success Response:Code: 200
    Content: { Id: 2, name : "Delhi" }
  • Error Response:Code: 404 NOT FOUND
    Content: { Response : null }
  • Sample Call: $.ajax({
    url: "/City/108",
    dataType: "json",
    type : "GET",
    success : function(r) {
    console.log(r);
    } });

Testing:

There are a lot of tools available in the market like Soap UI, JMeter, etc. But building continuous Integration with these tools can be a challenging task. It can be troublesome for developers to run these tools. So, the solution must be written in developer’s language.

Visual Studio has NuGet Package Called RestSharp and Newtonsoft JSON which makes the task easier for testing Rest API in a Black Box Manner.

RestSharp can send an API Get, PUT, Post, Delete and Patch Request and can get the response back from the API. In the Response, we can Check API for proper status Code, status Message, an assertion for specific JSON or XML Data.

Newtonsoft.json can deserialize JSON c#, which can be useful to get a JSON “Authentication Token” from the response body of the request. It helps to chain the request and makes life easy.

Steps for Solution:

  • Open The Visual Studio
  • Create a New Console Application in the Visual Studio
  • Add NuGet RestSharp, Newtonsoft.json Package to the Solution
  • Write a Post Request
  • Deserialize the JSON Request and fetch the authentication token from the response of the API
  • Assert the API for the Status Code and Status Response.
  • After getting token from the first API (login API) it can be passed to another API as well

These are the basic things to be taken care to design RESTful API structure; Stay tuned for our next article very soon.

We 9series, as an organization always try to serve best quality work to our esteemed clients; our expert team of engineers takes care of all small entities and requirements for the physical environment to host APIs and the way it’s constructed.

Recent Posts

  • Deep Learning Explained: Understanding the Brain Behind AI

  • The Intersection of AI and IoT: Creating Smarter, Connected Environments

  • The Evolution of AI: From Simple Algorithms to Neural Networks

  • The Role of AI in Sustainable Development

  • Scaling New Heights: Integrating Advanced Technologies in Startup Product Engineering

Categories

  • .Net MVC (3)
  • AI Solutions (7)
  • Amazon DynamoDB (1)
  • Amazon Web Services (AWS) (1)
  • Android (25)
  • Android App Developers (3)
  • Android app development (8)
  • Angularjs Development (4)
  • Apple (25)
  • Artificial Intelligence (6)
  • Artificial Intelligence Solutions (4)
  • Beacon Technology (4)
  • Best Christmas Offer (2)
  • Blockchain Technology (2)
  • ChatGPT (1)
  • Cloud Service (4)
  • Clutch (1)
  • Collaboration (1)
  • custom mobile app development services (4)
  • DevOps (2)
  • Digital Engineering Landscape (1)
  • Digital Marketing (9)
  • Django (2)
  • Docker (12)
  • E-Learning Technology (3)
  • Ecommerce (1)
  • Events (4)
  • Flutter app development (3)
  • GDPR (1)
  • Google I/O (1)
  • Graphic Design (12)
  • html5 developers (2)
  • Human Resource (5)
  • important for an organization (2)
  • Infographics (33)
  • iOS (21)
  • Laravel Development (2)
  • Large Language Models (2)
  • machine development companies in India (1)
  • machine development services in India (1)
  • Machine Learning (10)
  • machine learning development company (1)
  • machine learning development services (1)
  • Market Research Companies (11)
  • Marketing (9)
  • mean stack development (1)
  • Microsoft (11)
  • Mobile App Design (3)
  • Mobile App Development (53)
  • Moodle Development (1)
  • next-generation technology (7)
  • Node.js (2)
  • Online Marketing (1)
  • Open Source (11)
  • open source Javascript framework (1)
  • Opening Ceremony (1)
  • Python (3)
  • Python Development (4)
  • Responsive Website Development (9)
  • SaaS App Development (2)
  • Search Engine Optimization (4)
  • Social Media Marketing (2)
  • Software Development Company (2)
  • Technology (45)
  • Testing (11)
  • Top Laravel Development (2)
  • Travel and Hospitality Technology Solution (4)
  • Typescript (1)
  • UI Design Company India (1)
  • UI Design Services (2)
  • UI/UX Design (12)
  • Uncategorized (11)
  • VueJS (3)
  • Web Application Development (9)
  • Website Design (2)
  • Website Development Company (8)

Archives