A Look at REST API Design Patterns

2021.03.14 15:34

졸리운_곰 조회 수:120

A Look at REST API Design Patterns

In this article, we talk a bit about useful and intuitive design patterns in RestFul Webservice API architecture.

In this article, we talk a bit about useful and intuitive design patterns in RestFul Webservice API architecture. In general, design patterns are formalized best practices that a programmer can use to solve common problems when designing an application or system. Below are different elements of design patterns for a REST architecture. 

REST architecture style constraints: There are design rules that are applied to establish the different characteristics of the REST architectural style, which are referred to as REST constraints: 

layered system

  1. Client-server
  2. Statelessness
  3. Cacheable
  4. Uniform interface
  5. Layered systems

Goals of RESTful API design: Restful APIs should be straightforward, unambiguous, easy to consume, well-structured, and most importantly, accessible with well-known and standardized HTTP methods.

API design goals:

1. Affordance

Affordance is the possibility of an action on an object or environment. An API with clear perceived affordance allows the developer to understand its purpose and to use it seamlessly inside the Cybernetic Environment it was designed for.

2. Loosely Coupled

In Restful APIs, multiple clients are connected to the same backend server. So when the internal representation of a server is changed, it should not affect API consumption at the client-side. In a loosely coupled design, APIs are independent, and modifications in one won't impact the operation of consumers. Within an API, the components get added, modified, or replaced. However, the loose coupling approach offers clients better flexibility and reusability of APIs while its elements are added, replaced, or changed. Well-designed APIs exhibit loose coupling and well-composed functionalities across service boundaries to maximize scalability factors.

3. Leverage Existing Web Architecture

RESTful APIs should use HTTP as a transport layer since the infrastructure, server, and client libraries for HTTP are widely available already. RESTful APIs should take advantage of HTTP methods, or verbs, such as GET, PUT, and POST.  

RESTful API Design Patterns: API design patterns provide a description or templates to solve specific, recurring API design problems that any software architects and API designers would like to adopt in their API designs. 

1. Statelessness

Communication between client and server should be stateless, which means that every client request contains all the information necessary for the server to process the request. So there is no global state thereby reducing the complexity of the server. 

The good news is that some Restful web frameworks provide an out-of-the-box implementation for Statelessness. For example Spring Boot's REST API framework. 

2. Content Negotiation

Content-negotiation is a mechanism or process that services and clients can select as their resource representation format for their communication and handshakes during their usual course of communication.

HTTP specification comes up with a set of standard headers, through which the client can get information about a requested resource and carry the messages that indicate its representations.

So, for content negotiation, REST services need to use HTTP headers; that is, when the client makes requests, it includes the accepts header, the list of file types that the client and server can handle with no additional steps to the client requests, the server processes, and replies.

E.g. In Java we can use produces property in @GetMapping annotation 

@GetMapping(path="/investors/{investorId}/stocks/{symbol}", produces={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})

3. URI Templates

It is always the case that the client may need to include some additional information in their request, and how the server lets the client include that information about resources in the URIs. Server-side developers require the ability to describe the layout of the URIs that their services will respond to. So we can use the URI template. URI templates provide a way to describe a set of resources as variables. 

E.g. If there are multiple resources,

People: https://swapi.co/api/people/

Planets: https://swapi.co/api/planets/

Films: https://swapi.co/api/films/

Species: https://swapi.co/api/species/

We can use simply https://swapi.co/api/{resource_id}/ as a URI template

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 The @PathVariable annotation provided by Spring Boot helps us implement the URI template pattern in our code seamlessly. 

4. Design for Intent

Design for intent is a method that expresses the different relationships between objects so that changes to one object automatically propagates changes to others.

In a RESTful API world, the API should be developed to ensure they meet the requirements of the desired use cases provided and faced by users, but without exposing the internal business objects. Design for intent is a strategic design pattern that's intended to influence or result in specific and additional user behaviors.

5. Pagination

When there are multiple rows of data available then APIs should give the requested data in batch-wise (Pagination). 

Pagination is a concept that helps in serving only part of the data as a response, however, with information about how to access all the data from the server, page by page, without much load and high computation for the server to serve the whole data.

 E.g. xxx.api.com/students?page=2.

There are three variants of resource representation ways of pagination:

  1. Offset-based
  2. Time-based
  3. Cursor-based

5. Discoverability

Discoverability is a very important factor in API designing, helping developers figure out programmatically whether the site that's being accessed has an API enabled or not will be the most critical responsibility of the API.

Using the following two ways we can ensure discoverability of API for developers,

1. By Valid HTTP Methods

When clients call REST services with invalid HTTP methods, the response of that request should end up in the 405 HTTP error code; that is, 405 Method Not Allowed. In addition to the error code, the response header should provide flexibility to the client to find the supported methods that allow headers in its response. 

2. Providing the URI of the Newly Created Resource

Including the URI as part of the location header as the response to the newly created resource is another method of discoverability. The returned URI as a location will be available through GET. 

In Sprint boot it gives out-of-the-box solutions for discoverability E.g. Using @GetMapping annotation.

6. Unicode

A simple yet powerful way to make API support multiple languages is to enable the API to support Unicode.

Unicode is an encoding standard that supports an international character set. It has a unique number for every character across multiple languages including Chinese, Korean, and Arabic, and their scripts. The unique number makes almost all characters identifiable and accessible across platforms, programs, and devices.

API Design Principles

In general, the following standard guidelines should be followed while designing high-quality Restful APIs.

  1. Ubiquitous web standards
  2. Flexibility
  3. Standardization
  4. Optimization
  5. Granularity
  6. Sandbox or playground

api example design

This should be an excellent starting point for anyone who wants to get their hands into RESTful services, with not just the basics, but essential patterns as well. The enemy of design patterns are anti-patterns, which seem sounds but are counter-productive when executed. Unfortunately, anti-patterns are hard to detect. Read more about how a free static analyzer like Embold detects up to 30 structural design issues in Java programming. You can check out my other article on anti-patterns as well. 

Did you find this useful? Please comment.

 

[출처] https://dzone.com/articles/a-look-at-rest-api-design-patterns

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
» A Look at REST API Design Patterns file 졸리운_곰 2021.03.14 120
997 서버 확장을 위한 두 가지 방법: 스케일 아웃과 스케일 업 file 졸리운_곰 2021.03.07 83
996 [Apache Multi Domain] 아파치 멀티 도메인 : 이름기반 VirtualHost 설정 졸리운_곰 2021.02.13 541
995 Xampp virtualhost setting not working : Xampp Virtual Host: How to configure Virtual Host in Xampp file 졸리운_곰 2021.02.13 91
994 XAMPP 가상호스트 설정과 도메인 연결 file 졸리운_곰 2021.02.12 143
993 텍스트를 음성 mp3로 간단하게 변환하기 (With Naver Cloud Platform) : 딥러닝 몰라도 TTS 하는 법 file 졸리운_곰 2021.02.10 126
992 시각화 대시보드 를 만들기 위해 고려해야 하는 4가지 file 졸리운_곰 2021.02.10 178
991 gRPC 훑어보기 file 졸리운_곰 2021.02.10 105
990 [MSDOS app] 하늘 3.2 file 졸리운_곰 2021.01.29 82
989 한글 인코딩 정리 (자바를 중심으로) 졸리운_곰 2021.01.29 96
988 한글 도깨비 5.1 소프트웨어 버전 file 졸리운_곰 2021.01.26 194
987 아래아 한글 2.1 일반용 file 졸리운_곰 2021.01.26 85
986 아래아 한글 1.51 file 졸리운_곰 2021.01.26 91
985 NEMESIS Go Master 3.2 (바둑) file 졸리운_곰 2021.01.26 73
984 미니 한글 라이브러리 file 졸리운_곰 2021.01.26 121
983 한글 인코딩의 이해 2편: 유니코드와 Java를 이용한 한글 처리 file 졸리운_곰 2021.01.26 112
982 한글 인코딩의 이해 1편: 한글 인코딩의 역사와 유니코드 졸리운_곰 2021.01.26 86
981 한글 인코딩의 이해(유니코드) 완전 기초! file 졸리운_곰 2021.01.26 147
980 Quick Basic 4.5 file 졸리운_곰 2021.01.25 71
979 컴퓨터 속의 한글 도서 부록 디스켓 file 졸리운_곰 2021.01.25 75
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED