RESTful API의 페이지 매김 응답 페이로드
RESTful API에서 페이지 매김을 지원하고 싶습니다.
내 API 메서드는 .NET을 통해 제품의 JSON 목록을 반환해야합니다 /products/index. 그러나 잠재적으로 수천 개의 제품이 있으며 페이지를 넘기고 싶으므로 내 요청은 다음과 같아야합니다.
/products/index?page_number=5&page_size=20
하지만 내 JSON 응답은 어떤 모습이어야합니까? API 소비자는 일반적으로 응답에서 페이지 매김 메타 데이터를 기대합니까? 아니면 다양한 제품 만 필요합니까? 왜?
Twitter의 API에 메타 데이터가 포함되어있는 것 같습니다 : https://dev.twitter.com/docs/api/1/get/lists/members (예제 요청 참조).
메타 데이터 사용 :
{
"page_number": 5,
"page_size": 20,
"total_record_count": 521,
"records": [
{
"id": 1,
"name": "Widget #1"
},
{
"id": 2,
"name": "Widget #2"
},
{
"id": 3,
"name": "Widget #3"
}
]
}
제품 배열 (메타 데이터 없음) :
[
{
"id": 1,
"name": "Widget #1"
},
{
"id": 2,
"name": "Widget #2"
},
{
"id": 3,
"name": "Widget #3"
}
]
ReSTful API는 주로 다른 시스템에서 사용되기 때문에 응답 헤더에 페이징 데이터를 넣습니다. 그러나 일부 API 소비자는 응답 헤더에 직접 액세스 할 수 없거나 API를 통해 UX를 구축 할 수 있으므로 요청시 JSON 응답에서 메타 데이터를 검색하는 방법을 제공하는 것이 장점입니다.
구현에는 기계가 읽을 수있는 메타 데이터가 기본으로 포함되어야하고 요청시 사람이 읽을 수있는 메타 데이터가 포함되어야한다고 생각합니다. 사람이 읽을 수있는 메타 데이터는 원하는 경우 모든 요청과 함께 반환 될 수 있으며, 가급적이면 include=metadata또는 같은 쿼리 매개 변수를 통해 요청시 반환 될 수 있습니다 include_metadata=true.
특정 시나리오에서는 레코드와 함께 각 제품의 URI를 포함합니다. 이렇게하면 API 소비자가 개별 제품에 대한 링크를 쉽게 만들 수 있습니다. 또한 페이징 요청의 한계에 따라 합리적인 기대치를 설정했습니다. 페이지 크기에 대한 기본 설정을 구현하고 문서화하는 것이 허용되는 방법입니다. 예를 들어 GitHub의 API 는 기본 페이지 크기를 최대 100 개의 레코드 30 개로 설정하고 API를 쿼리 할 수있는 횟수에 대한 속도 제한을 설정합니다. API에 기본 페이지 크기가있는 경우 쿼리 문자열은 페이지 색인 만 지정할 수 있습니다.
사람이 읽을 수있는 시나리오에서로 이동할 때 /products?page=5&per_page=20&include=metadata응답은 다음과 같을 수 있습니다.
{
"_metadata":
{
"page": 5,
"per_page": 20,
"page_count": 20,
"total_count": 521,
"Links": [
{"self": "/products?page=5&per_page=20"},
{"first": "/products?page=0&per_page=20"},
{"previous": "/products?page=4&per_page=20"},
{"next": "/products?page=6&per_page=20"},
{"last": "/products?page=26&per_page=20"},
]
},
"records": [
{
"id": 1,
"name": "Widget #1",
"uri": "/products/1"
},
{
"id": 2,
"name": "Widget #2",
"uri": "/products/2"
},
{
"id": 3,
"name": "Widget #3",
"uri": "/products/3"
}
]
}
컴퓨터에서 읽을 수있는 메타 데이터의 경우 응답에 링크 헤더 를 추가 합니다.
Link: </products?page=5&perPage=20>;rel=self,</products?page=0&perPage=20>;rel=first,</products?page=4&perPage=20>;rel=previous,</products?page=6&perPage=20>;rel=next,</products?page=26&perPage=20>;rel=last
(the Link header value should be urlencoded)
...and possibly a custom total-count response header, if you so choose:
total-count: 521
The other paging data revealed in the human-centric metadata might be superfluous for machine-centric metadata, as the link headers let me know which page I am on and the number per page, and I can quickly retrieve the number of records in the array. Therefore, I would probably only create a header for the total count. You can always change your mind later and add more metadata.
As an aside, you may notice I removed /index from your URI. A generally accepted convention is to have your ReST endpoint expose collections. Having /index at the end muddies that up slightly.
These are just a few things I like to have when consuming/creating an API. Hope that helps!
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
- Without the total count, how can the client know that it has not yet received everything there is and should continue paging through the result set? In a UI that didn't perform look ahead to the next page, in the worst case this might be represented as a Next/More link that didn't actually fetch any more data.
- Including metadata in the response allows the client to track less state. Now I don't have to match up my REST request with the response, as the response contains the metadata necessary to reconstruct the request state (in this case the cursor into the dataset).
- If the state is part of the response, I can perform multiple requests into the same dataset simultaneously, and I can handle the requests in any order they happen to arrive in which is not necessarily the order I made the requests in.
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
I would recommend adding headers for the same. Moving metadata to headers helps in getting rid of envelops like result , data or records and response body only contains the data we need. You can use Link header if you generate pagination links too.
HTTP/1.1 200
Pagination-Count: 100
Pagination-Page: 5
Pagination-Limit: 20
Content-Type: application/json
[
{
"id": 10,
"name": "shirt",
"color": "red",
"price": "$23"
},
{
"id": 11,
"name": "shirt",
"color": "blue",
"price": "$25"
}
]
For details refer to:
https://github.com/adnan-kamili/rest-api-response-format
For swagger file:
https://github.com/adnan-kamili/swagger-response-template
generally, I make by simple way, whatever, I create a restAPI endpoint for example "localhost/api/method/:lastIdObtained/:countDateToReturn" with theses parameters, you can do it a simple request. in the service, eg. .net
jsonData function(lastIdObtained,countDatetoReturn){
'... write your code as you wish..'
and into select query make a filter
select top countDatetoreturn tt.id,tt.desc
from tbANyThing tt
where id > lastIdObtained
order by id
}
In Ionic, when I scroll from bottom to top, I pass the zero value, when I get the answer, I set the value of the last id obtained, and when I slide from top to bottom, I pass the last registration id I got
참고URL : https://stackoverflow.com/questions/12168624/pagination-response-payload-from-a-restful-api
'Nice programing' 카테고리의 다른 글
| LinearLayout 대 RelativeLayout (0) | 2020.10.30 |
|---|---|
| 수직으로 고정 된 위치 요소, 절대 수평으로 고정 (0) | 2020.10.30 |
| Node js와 express js의 차이점 (0) | 2020.10.29 |
| 중첩 조인이있는 PostgreSQL 9.2 row_to_json () (0) | 2020.10.29 |
| 풀 요청 / 문제를 연결하는 Github 커밋 구문 (0) | 2020.10.29 |