partkyle
partkyle

Reputation: 1458

Flask: Getting request parameters based on Content-Type header

What is the proper way to deal with the request body depending on the Content-Type header of the request?

I need to implement a RESTful service that supports XML, JSON and form encoded request parameters, but I can't seem to find a clean way of extracting the request parameters.

Is this something that I should use a middleware for? Do I need to extend the Request object?

I haven't found any packages that do this, and it seems like a pretty common task for creating RESTful services in flask.

Upvotes: 3

Views: 4487

Answers (2)

Gabe Moothart
Gabe Moothart

Reputation: 32072

You could use @app.before_request as illustrated here. Once you've done your thing normalizing the request params, you can save them to g, something like this:

from flask import g
from flask import request
...


@app.before_request
def before_request():
    # normalize params based on Content-Type
    g.params = normalized_params

Upvotes: 0

Audrius Kažukauskas
Audrius Kažukauskas

Reputation: 13533

You probably meant Accept header, as Content-Type is used for response. There are three choices here:

  1. Build it youself as described in Handling Accept Headers snippet.
  2. Use Flask-RESTful extension (consult Content Negotiation part in the docs).
  3. Use Flask-Pushrod extension which is specifically built to handle this case.

Upvotes: 2

Related Questions