MySQLを利用したFlask RESTful API作成(2)

MySQLを利用したFlask RESTful API作成(1) - マイノート


最後に"/"を入れなくてもいいようにしたい

$ curl http://localhost:5000/users/1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="http://localhost:5000/users/1/">http://localhost:5000/users/1/</a>. If not click the link.

最後に"/"がないといけないみたい。


Automatic redirect with "/" breaks routes with different methods #1783
https://github.com/pallets/flask/issues/1783


app.pyを修正する
#@app.route('/users/', methods=['POST']) ←コメントアウトし、以下の行を追加する
@app.route('/users/', methods=['POST'], strict_slashes=False)
...
#@app.route('/users/<string:uid>>/', methods=['GET']) ←コメントアウトし、以下の行を追加する
@app.route('/users/<string:uid>/', methods=['GET'], strict_slashes=False)
...


実行する

$ curl http://localhost:5000/users/1
{
  "email_address": "test@example.com", 
  "id": 1, 
  "name": "test"
}
$ curl -X POST -H "Content-Type: application/json" -d '{"name":"test4", "email_address":"test4@example.com"}' http://localhost:5000/users
{
  "email_address": "test4@example.com", 
  "name": "test4"
}

APIに外部からアクセスできない!

外からアクセスすると、拒否される。。

$ curl http://192.168.0.35:5000/users/1
curl: (7) Failed to connect to 192.168.0.35 port 5000: Connection refused


Flaskのサーバーはデフォルトだと公開されてない
https://qiita.com/tomboyboy/items/122dfdb41188176e45b5


app.pyを修正する
#app.run(debug=True) ←コメントアウトし、以下の行を追加する
app.run(debug=True, host='0.0.0.0', port=8000)

$ curl http://192.168.0.35:8000/users/1
{
  "email_address": "test@example.com",
  "id": 1,
  "name": "test"
}

やっと外からもアクセスできるようになった。




このあと、テーブルをjoinした結果をAPIで返したかったが、marshmallowのスキーマのところがよくわからなかったので断念した。