A Look at REST API Design Patterns

2021.03.14 15:34

졸리운_곰 조회 수:12

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

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
1115 [ 一日30分 인생승리의 학습법] 2023 네이버 다이어리 굿노트 템플릿으로 심플하게 새해 계획 file 졸리운_곰 2023.01.07 15
1114 [ 一日30分 인생승리의 학습법] 프로그래밍 스킴 Scheme 1 다운로드부터 문법 대부분을 314초만에 알려줄게요 졸리운_곰 2023.01.05 5
1113 [ 一日30分 인생승리의 학습법] ROBOCOPY(로보카피) 사용법 file 졸리운_곰 2023.01.05 10
1112 [ 一日30分 인생승리의 학습법] PHP, VBA and SQL Useful Scripts PHP, VBA 및 SQL 유용한 스크립트 file 졸리운_곰 2023.01.01 7
1111 [ 一日30分 인생승리의 학습법] KoELECTRA로 기계독해(MRC) API 개발 file 졸리운_곰 2023.01.01 7
1110 [ 一日30分 인생승리의 학습법] 일 안 해도 생기는 수입? 그런 ‘패시브 인컴’은 없다 file 졸리운_곰 2023.01.01 6
1109 [ 一日30分 인생승리의 학습법] Qemu를 이용한 가상화 기초 file 졸리운_곰 2022.12.31 5
1108 [ 一日30分 인생승리의 학습법] 파이토치로 딥러닝해야 하는 5가지 이유 졸리운_곰 2022.12.31 6
1107 [ 一日30分 인생승리의 학습법] 왜 ‘한국어’의 자연어처리(NLP)는 유독 어려울까? file 졸리운_곰 2022.12.31 10
1106 [ 一日30分 인생승리의 학습법] MinIO Windows Service 등록 졸리운_곰 2022.12.24 7
1105 [ 一日30分 인생승리의 학습법] Apache 2.2에서 2.4로 마이그레이션 시 발생하는 에러 및 해결책 정리 졸리운_곰 2022.12.18 6
1104 [ 一日30分 인생승리의 학습법] Git 사용 방법 정리(commit, push, pull request, merge 등) 졸리운_곰 2022.12.04 18
1103 [ 一日30分 인생승리의 학습법] [웹 기획] 화면 설계 용어 - 와이어프레임, 스토리보드, 프로토타입의 차이점 file 졸리운_곰 2022.12.03 6
1102 [ 一日30分 인생승리의 학습법] REST API 설계 (네이밍) 졸리운_곰 2022.11.26 24
1101 [ 一日30分 인생승리의 학습법] REST API URI 규칙 졸리운_곰 2022.11.26 12
1100 [ 一日30分 인생승리의 학습법 ] REST API URL 규칙 졸리운_곰 2022.11.26 9
1099 [ 一日30分 인생승리의 학습법 ] prolog 문법 : Prolog Syntax 졸리운_곰 2022.11.21 3
1098 [ 一日30分 인생승리의 학습법 ] noVNC 작동원리 file 졸리운_곰 2022.11.16 8
1097 [ 一日30分 인생승리의 학습법 ] 프로젝트 만들고 GitHub에 첫 Commit하고 Push하기 file 졸리운_곰 2022.11.15 4
1096 [ 一日30分 인생승리의 학습법 ] 우분투(리눅스) 에서 EBS 라디오 자동녹음 만들기 졸리운_곰 2022.11.11 9
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED