I am making a Web API for a Python program I wrote, I am copying a tutorial.
This is the API code:
#!flask/bin/python
from flask import Flask
from flask import make_response
from flask import request
import requests
import json
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
@app.route('/5492946838458/index.html', methods=['POST'])
def create_task():
if not request.json or not 'key' in request.json or not 'name' in request.json or not 'text' in request.json or not 'pack' in request.json:
abort(400)
if 'title' in request.json and type(request.json['title']) != unicode:
abort(400)
if 'description' in request.json and type(request.json['description']) is not unicode:
abort(400)
task = {
'key': request.json['key'],
'name': request.json['name'],
'text': request.json['text'],
'pack': request.json['pack']
}
return (200)
This is the URL I'm sending it to
https://my.websites.url.here/5492946838458/
and the json data I'm sending
{
"key": "key",
"name": "name",
"text": "text",
"pack": "pack"
}
and the headers I get back I get
date: Fri, 04 Sep 2020 17:48:30 GMT
content-length: 0
vary: Origin
accept-ranges: bytes
allow: GET, HEAD, OPTIONS
Why does this happen and how can I fix this?
Two problems I can see...
This line shouldn't be floating in the middle of your code. It should be at the very end:
if __name__ == '__main__':
app.run(debug=True)
With its current placement, if you're executing the app with python app.py
, the app will run at this point. Routes before it (index
) will be available, however routes declared after it (create_task
) will not (until you kill the server - when the latter route is added, right before the python
process stops).
This problem wouldn't be seen if executing with flask run
as the if
clause is False.
@app.route('/5492946838458/index.html', methods=['POST'])
for this one you're probably want:
@app.route('/5492946838458/', methods=['POST'])
This declares the URL of that route.
Now a request to https://my.websites.url.here/5492946838458/
should return a successful response. A request to /5492946838458
will return a 308 redirect to the one with the trailing slash.
I'm not sure why you were getting 405
before. Perhaps there's aother route somewhere in your code accepting the request, but not the method.