LoginSignup
55
39

More than 3 years have passed since last update.

JSONでPOSTしたものをpythonで使う方法

Last updated at Posted at 2018-01-22

自作API(flask使用)を試す時にcurlを使ってJSONをPOSTしようと思ったらハマったのでメモ

まずcurlを使ってデータをPOSTするのに

curl http://localhost:8000/post_data -X POST -H "Content-Type: application/json" --data '{"key": "value"}'

ってやったらb'{"key":"value"}'の形でPOSTされる。
最初はここをあまり詳しく見ていなくて

@app.route('/post_data', methods=['GET', 'POST'])
def check():
    if request.method == 'POST':
        data = request.data['key']

って使っていたのでエラーが出た。
curlのオプション指定が悪いのかなぁとか思ったけどこれ以外になさそうなので多分オプション指定は間違えていない。

@app.route('/post_data', methods=['GET', 'POST'])
def check():
    if request.method == 'POST':
        data = request.data.decode('utf-8')
        data = json.loads(data)
        img_url = str(data['key'])

って感じでbytes型をstringに変換してそこからjsonに変換して使用。

追記(2020年5月13日)

記事投稿時(2018年1月)からflaskに触れておらず知らなかったのですが
今は

@app.route('/post_data', methods=['GET', 'POST'])
def check():
    if request.method == 'POST':
        data = request.json['key']

こちらでいけるみたいです。(mimeがapplication/jsonで送られている場合)
これなら苦しまなさそう!
参考

55
39
3

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
55
39