Bradley Joe
Bradley Joe

Reputation: 61

POST requests gives 405 error on Python flask server

I am trying to do a POST request using python requests and flask, however the server gives a 405 error.

Client:

import json
import requests

payload = {'firstname':'John', 'lastname':'Smith'}

url = 'http://localhost:5000/order'

r = requests.post(url,json=payload)

Server:

from flask import Flask
app = Flask(__name__)

@app.route('/order', method='POST')
   def getjson():
       print('hello')

When I try this code on the client side it works fine:

r = requests.get('http://localhost:5000/order')
print(r.status_code)

Any ideas why? Thanks

Upvotes: 0

Views: 1164

Answers (1)

arshovon
arshovon

Reputation: 13651

Error 405 Method Not Allowed indicates that the request from client is not a valid request format. Details of 405 error can be found in Mozilla's documentation on HTTP 405 error code.

I have updated the typo in server Python code. Also updated the client code to send the JSON properly.

Server:

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/order', methods=['POST'])
def getjson():
    content = request.json
    return jsonify(content)

Client:

import json
import requests

payload = {'firstname':'John', 'lastname':'Smith'}
url = 'http://localhost:5000/order'
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.status_code)
print(r.json())

Client output:

200
{'firstname': 'John', 'lastname': 'Smith'}

Upvotes: 1

Related Questions