Search code examples
pythontwitterpython-requestshttp-get

How to encode an array as a http get parameter?


My goal is to send an API request with an array as a parameter value. The request-URL is https://api.twitter.com/2/tweets/search/recent?max_results=100&tweet.fields=lang,created_at&query=%23test.When I'm using the URL as a string it works.

However, since it's more convenient to work with a dictionary of arguments I wanted to use the syntax response = requests.request('GET', url, headers=header, params=params) as it allows me to set all the parameters within a single object.

For this, my parameter dictionary looks like this.

params = {
    "max_results": 100,
    "tweet.fields": ["lang","created_at"],
    "query": "%23test"
}

The problem here is the resulting URL https://api.twitter.com/2/tweets/search/recent?max_results=100&tweet.fields=lang&tweet.fields=created_at&query=%23test.

This URL won't work as tweet.fields is encoded with tweet.fields=lang&tweet.fields=created_at which violates the duplicate parameter policy of Twitter.

'{"errors":[{"parameters":{"tweet.fields":["lang","created_at"]},"message":"Duplicate parameters are not allowed:  the `tweet.fields` query parameter"}],"title":"Invalid Request","detail":"One or more parameters to your request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}'

Another idea was to change the parameters to "tweet.fields": {"lang","created_at"}, which results in the same URL as the other parameter dictionary.

How would I encode the parameter in a way that the parameter will be encoded as tweet.fields=lang,created_at rather than tweet.fields=lang&tweet.fields=created_at while keep using the parameter dictionary?


Solution

  • If you need a string like lang, created_at then simply place one there.

    params = {
        "max_results": 100,
        "tweet.fields": "lang,created_at",
        "query": "%23test"
    }
    

    You can also automatically generate one with .join method.

    params = {
        "max_results": 100,
        "tweet.fields": ",".join(["lang", "created_at"]) ,
        "query": "%23test"
    }