0
/api/stats
?fields=["clkCnt","impCnt"]
&ids=nkw0001,nkw0002,nkw0003,nkw0004
&timeRange={"since":"2019-05-25","until":"2019-06-17"}

I'm currently working on a API called naver_searchad_api link to github of the api If you want to check it out. but i don't think you need to

the final url should be a baseurl + /api/stats and on fields and ids and timeRange, the url should be like that

the requests I wrote is like below

r = requests.get(BASE_URL + uri, params={'ids': ['nkw0001','nkw0002','nkw0003','nkw0004'], 'timeRange': {"since": "2019-05-25", "until": "2019-06-17"}}, headers=get_header(method,uri,API_KEY,SECRET_KEY,CUSTOMER_ID))
final_result = r.json()
print(final_result)

as I did below instead

print(r.url)

it returns as below

https://api.naver.com/stats?ids=nkw0001&ids=nkw0002&ids=nkw0002&ids=nkw0002&fields=clkCnt&fields=impCnt&timeRange=since&timeRange=until

the 'ids' is repeated and doesn't have dates that I put.

how would I make my code to fit with the right url?

1
  • please add the output of print(r.url) Commented Jun 25, 2019 at 14:08

1 Answer 1

1

Query strings are key-value pairs. All keys and all values are strings. Anything that is not trivially convertible to string depends on convention. In other words, there is no standard for these things, so it depends on the expectations of the API.

For example, the API could define that lists of values are to be given as comma-separated strings, or it could say that anything complex should be JSON-encoded.

In fact, that's exactly what the API documentation says:

fields   string  
Fields to be retrieved (JSON format string).

For example, ["impCnt","clkCnt","salesAmt","crto"]

The same goes for timeRange. The other values can be left alone. Therefore we JSON-encode those two values only.

We can do that inline with a dict comprehension.

import json
import requests

params = {
    'fields': ["clkCnt", "impCnt"],
    'ids': 'nkw0001,nkw0002,nkw0003,nkw0004',
    'timeRange': {"since":"2019-05-25","until":"2019-06-17"},
}

resp = requests.get('https://api.naver.com/api/stats', {
    key: json.dumps(value) if key in ['fields', 'timeRange'] else value for key, value in params.items()
})

On top of complying with the API's expectations, all keys and values that go into the query string need to be URL-encoded. Luckily the requests module takes care of that part, so all we need to do is pass a dict to requests.get.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for your kind explanation. I learned so much from you.
Yes, that looks better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.