관리 메뉴

Silver Library (Archived)

미궁 같았던 query parameter in rest api 본문

카테고리 없음

미궁 같았던 query parameter in rest api

Chesed Kim 2022. 10. 23. 17:12
반응형

이게 정말 미궁같았던게,

console.log 를 쳐서, 이리저리 해 봐도 표시가 되긴 하지만...

도대체 언제 저 parameter를 쓰되, 저걸 쓰는 도중에 쓰이는 저 equal sign 이나 &는 왜 쓰는 걸까?

 

[참조 : 필자는 생활적 편의상 영어를 일부 혼용해서 작성했습니다. 개발자가 갖춰야 할 능력 같은거나 잘난척의 목적 하고는 무관계합니다.]

 

이 문제의 원인.

초창기 이 부분을 다룰 시에는 클론 코딩으로 접하다 보니, 해당 방법을 설명하는 과정을 따라가는 쪽에 가까웠다.

어떻게 한다는 건 알지만, 이게 기초부터 다시 정립하고 이제 이걸 제대로 해 보려는 순간 '막힌다' 였다.

경제도 그렇지 않은가. 그냥 책만 읽는다고 되는게 아니듯이, 알고 접목해야만 효율과 지혜가 섞인 판단이 가능하다.

 

아무튼 그래서 다다른 첫번째 종착지가 바로 이 'query parameter'. 

우선 이 미궁을 해석하는 방법은...

1. 해당 api 의 document 를 참고.

2. 그 parameter 대상을 첨부할 시, 어떤 목적으로 하려는 건지?

 

그렇다. 어쩌면 당신이라면 알아차렸을 것이다.

아이쿠! query 하고 path parameter 에 대한 지식이 불안정했구나! 하고.

그렇게 그토록 찾던 문제의 근원을 찾았다.

 

https://branch.io/glossary/query-parameters/

 

Query Parameters

Branch's Glossary

branch.io

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a ‘?’ Is added followed immediately by a query parameter.

To add multiple parameters, an ‘&’ is added in between each. These can be created by any variation of object types or lengths such as String, Arrays and Numbers. The following is an example:

http://example.com/path?name=Branch&products=[Journeys,Email,Universal%20Ads]

It’s important to note that query parameters can play a role in attribution, although it’s also important to make sure that your attribution strategy is really cross-platform, and that it’s really doing everything for you that it can be. Click here to learn more about people-based, cross-platform attribution.

 

path?name=Branch&products 같은 경우, 볼 때 마다 '저거 무슨 공식이라도 있나' 라던 그 부분이었다.

 

그럼 path parameter 는?

 

What are Path Parameters? Technical topics explained simply

Everything you need to know about Path Parameters. This article will give you examples of Path Parameters, explain Query Parameters, and more.

www.abstractapi.com

What are Path Parameters?

Path parameters are request parameters attached to a URL that point to a specific REST API resource. The path parameter is separated from the URL by a `/`, and from the query parameter(s) by a question mark (`?`). The path parameter defines the resource location, while the query parameter defines sort, pagination, or filter operations. The user's input (the query) is passed as a variable in the query parameter, while each path parameter must be substituted with an actual value when the client makes an API call. The path parameter is contained within curly braces.

Path Parameter Example

Path parameters are part of the endpoint and are required. For example, `/users/{id}`, `{id}` is the path parameter of the endpoint `/users`- it is pointing to a specific user's record. An endpoint can have multiple path parameters, like in the example `/organizations/{orgId}/members/{memberId}`. This would be pointing to a specific member's record within a specific organization, with both `{orgID}` and `{memberID}` requiring variables.

Path vs query parameters

Path parameter values are perhaps not as exciting and customizable as query parameters, but no matter how cleverly you query, you won't find a resource if you're looking in the wrong place! Path parameters offer a very human-readable way of understanding a resource location, similar to a local file location like `C:/Program Files/Program`. It's where we want to look for key-value pairs from the request header.

Path parameter API tutorial

Let's say we want to [call](/what-is-an-api-call.md) a weather API for our daily surf report:

```java curl /surfreport/beachId?days=3&units=metric&time=1400```

What do we see in this GET request?  

  • `/surfreport/{beachID}` `/surfreport` is the endpoint, and `beachID` is the path parameter. The `/surfreport/{beachID}` path parameter takes a geographic beach code to look up the resource associated with that code.
  • `?` is where our query string begins. This information is returned in a JSON file.

Conclusion

While query parameters describe how to look, path parameters show your program where to look. Path parameters are part of the endpoint URI and are required to have a value. Think of path parameters as the file system in your endpoint URL, guiding the request to the answer it seeks.

 

참고로 그냥 제공 uri 값 이외에 저런 식으로 path나 query 를 섞어서 사용할 때에는 back tick 으로 uri 를 감싸준다.

 

What is the difference between URL and URI in API?
URL and URI, both crucial concepts of the web, are terms that are often interchanged and used. However, they are not the same. The URI can represent both the URL and the URN of a resource, simultaneously, while URL can only specify the address of the resource on the internet.

자, 그렇게 해서 불러오는 건 해낼 수 있게 되었다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        fetch("https://api.jikan.moe/v4/top/anime?sfw=true&limit=10")
            .then((response) => response.json())
            .then(console.log);
            
    </script>
</body>
</html>