MDL
MDL

Reputation: 29

Falcon for building API

How do I obtain the req in falcon as json and not string as seperate key value pairs.

If {"a:213","b":32435} How do i make sure a is passed and then obtain value of a

Upvotes: 0

Views: 433

Answers (5)

LironAha
LironAha

Reputation: 1

after you translate the req/resp into JSON with:

json.load(req.stream)

you can look at the output as a regular dictionary.

Upvotes: 0

Ashwani Shakya
Ashwani Shakya

Reputation: 439

I hope following code will help you.

json_data = json.loads(req.stream.read())
try:
    value_a = json_data['a']
except KeyError as k:
    print 'a is not passed'

Upvotes: 2

user7776598
user7776598

Reputation:

Use

stream = req.bounded_stream.read() 

or

stream = req.stream.read()

I created a BodyParser class as a middleware:

class BodyParser(object):
    def __init__(self, ctx):
        self.ctx = ctx
    def process_request(self, req, resp):
        if req.method.upper() in ['POST', 'PUT', 'PATCH']:
            stream = req.stream.read()
            if not stream:
                req.context['body'] = None
                return
            req.context['body'] = json.loads(stream)

Hope it helps

Upvotes: 0

Harshad Kavathiya
Harshad Kavathiya

Reputation: 10234

I think following code will help you:

json_data = json.loads(req.stream.read())

OR if you want to specify specific encoding format of input data.

json_data = json.loads(req.stream.read().decode('utf8'))

Please let me know you need further clarification.

Upvotes: 1

joarleymoraes
joarleymoraes

Reputation: 1949

Not sure if that's what you asked, but you can transform you raw request (req) to json by using:

if req.content_length:
   doc = json.load(req.stream)

Upvotes: 0

Related Questions