1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでURLエンコードする際の初歩的なミス

Posted at

経緯

APIを使用するスクリプトの実装時にHPPTリクエスト(GET)を実行する必要がありました。
その際のパラメーターとして日本語を使用するので、
URLをエンコードする必要があったのですがその際にしてしまった初歩的なミスについて記載します。
※本当に情けないくらい初歩的なミスです。

初期実装

パラメーターをエンコードすればいいと思ったので以下のような実装をしていました。

import requests

parameter = 'パラメーター'.encode('utf-8')
url = 'https://api.url?parameter=' + parameter
res = requests.get(url)

上記のようなパラメーターのエンコードでGETしたところエラーになりました。
エンコードしたパラメーターを出力してみると

b'\xe3\x83\x91\xe3\x83\xa9\xe3\x83\xa1\xe3\x83\xbc\xe3\x82\xbf\xe3\x83\xbc'

のような形式で出力されていました。
これはさすがに違和感を覚えました。

修正後の実装

しかし、URLをエンコードする際はUTF-8でエンコードするのではなくパーセントURLでなければならないので、
以下のような実装でなければGETは通りません。

import requests
import urllib.parse

parameter = urllib.parse.quote('パラメーター')
url = 'https://api.url?parameter=' + parameter
res = requests.get(url)

パラメーターの出力結果は以下のようにパーセントエンコードになります。

%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E3%83%BC

上記の実装に修正したことで正常にGETできるようになりました。
以上です。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?