HTTP Method Overrides using X-HTTP-Method-Override
When requesting for Restful APIs of backend, somtimes OPTION request is sent prior to a POST request to inquire http method support abilities of the backend server. When if the server returns only GET and POST methods while you need to send a PUT/DELETE … request?
To solve this problem, commonly two methods can be used under different circumstances.
Method 1 is used to use a _method field in data to override a POST request. See a JQuery POST request as an example below.
$.ajax({
url:"http://localhost:8888/answer/"+answerId,
type:"POST",
data:{_method:"DELETE", id:issueId,userId:userId},
dataType:"json",
success:function(result){
}
},
});
Method 2 is to use X-HTTP-Method-Override header. Consider that if you’re writing a RIA client(Flex or silverlight), there would be no way to add _method field. So you have to use X-HTTP-Method-Override
header. See a Flask example below. Or check Flask offical document here.
class HTTPMethodOverrideMiddleware(object):
allowed_methods = frozenset([
'GET',
'HEAD',
'POST',
'DELETE',
'PUT',
'PATCH',
'OPTIONS'
])
bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE'])
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()
if method in self.allowed_methods:
method = method.encode('ascii', 'replace')
environ['REQUEST_METHOD'] = method
if method in self.bodyless_methods:
environ['CONTENT_LENGTH'] = '0'
return self.app(environ, start_response)
from flask import Flask
app = Flask(__name__)
app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)