0

I'm using python to encode my class to JSON, but when I make a PUT request, the raiser error says: bad request 400. But my JSONis valid, so I'm not sure why this error occurs.

import json
import requests

class Temperature:
    def __init__(self, value, type):
        self.value = value
        self.type = type
    def reprJSON(self):
        return dict(value=self.value, type=self.type)

class Occupation:
    def __init__(self, value, type):
        self.value = value
        self.type = type
    def reprJSON(self):
        return dict(value=self.value, type=self.type)

class MaxCapacity:
    def __init__(self, value, type):
        self.value = value
        self.type = type
    def reprJSON(self):
        return dict(value=self.value, type=self.type)

class Room:
    def __init__(self, id, type):
        self.id = id
        self.type = type
        self.temperature = Temperature('30','Float')
        self.occupation = Occupation('0','Integer')
        self.maxcapacity = MaxCapacity('50','Integer')
    def reprJSON(self):
        return dict(id=self.id, type=self.type, temperature=self.temperature, occupation=self.occupation, maxcapacity=self.maxcapacity)

    def createRoom(self):
        print("Creating Entity...")
        url = 'http://localhost:1026/v2/entities'
        headers = {'Content-Type': 'application/json'}
        payload = json.dumps(self.reprJSON(), cls=ComplexEncoder)
        print(payload)
        r = requests.post(url,json=payload)
        print(r.raise_for_status()) # status for debugging
        print(r.status_code)
        print("Entity Created successfully!")



class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj,'reprJSON'):
            return obj.reprJSON()
        else:
            return json.JSONEncoder.default(self, obj)

if __name__ == '__main__':

    room = Room('urn:ngsi-ld:Room:001','Room')
    room.createRoom()
    #room.createRoom(url, headers)

Actually, I'm receiving this error:

raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http://localhost:1026/v2/entities

I would expect POST to return successfully (code 201).

Szymon Maszke
  • 22,747
  • 4
  • 43
  • 83
  • There is no post request in your code ... the post creates your error. – Patrick Artner Mar 23 '19 at 12:24
  • Your JSON also does not tell you what class was serialized - how can you distinguish between an instance of `Temperature` , `Occupation` and `MaxCapacity`? All got the same attributes. Why do they not have a constructor accepting a JSON to create themselds as instance? – Patrick Artner Mar 23 '19 at 12:26
  • There are better ways to do what you want withput serializing yourself. **Possible duplicate** of: [How-to-make-a-class-json-serializable](https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable) – Patrick Artner Mar 23 '19 at 12:29

0 Answers0