SwiftとPythonでAPIサーバを作ってiOSからGET,POSTなどをしたいと思っています。ほぼ初心者です。
swift
1 @IBAction func actionCreate(_ sender: Any) { 2 Session.send(CreateBusinessTermRequest(id: titleTextField.text, name: contentTextField.text)) { result in 3 switch result { 4 case .success( _): 5 print("作成完了!") 6 case .failure(let err): 7 print("エラーが出ました。") 8 print(err) 9 } 10 } 11 }
swift
1struct CreateBusinessTermRequest: WebRequest { 2 3 var path: String { 4 return "/" 5 } 6 typealias Response = BusinessTerm 7 8 var method: HTTPMethod { 9 return .post 10 } 11 12 var id: String? 13 var name: String? 14 15 var bodyParameters: BodyParameters? { 16 return JSONBodyParameters(JSONObject: [ 17 "id": id, 18 "name": name 19 ]) 20 } 21 22 func response(from object: Any, urlResponse: HTTPURLResponse) throws -> CreateBusinessTermRequest.Response { 23 return try decodeValue(object) 24 } 25}
python
1class PostResource(object): 2 3 # postされた時の動作 4 def on_post(self, req, res): 5 6 body = req.stream.read() 7 data = json.loads(body) 8 9 # パラメーターの取得 10 name = data['name'] 11 id = data['id'] 12 13 connection = MySQLdb.connect( 14 host='localhost', 15 port=3306, 16 user='root', 17 passwd='password', 18 db='sample', 19 charset='utf8', 20 cursorclass=MySQLdb.cursors.DictCursor 21 ) 22 cursor = connection.cursor() 23 sql = "insert into business_term values(%d, '%s');"%(id, name) 24 25 cursor.execute(sql) 26 data = cursor.fetchall() 27 28 cursor.close() 29 connection.close() 30 31 res.status = falcon.HTTP_200 32 res.body = json.dumps(data) 33 print(res.body) 34
このようになっています。
Error
1responseError(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})
このようになっています。
JSONに関するロジックが噛み合わないような気がしていますが、原因を明確に突き止められません。
何か間違いや意見がありましたらお願いします。
あなたの回答
tips
プレビュー