0

I am trying to use python as a backend for my swift application. When i send the request to the server (flask) i can return a string back but can't use json.dumps() to re-create the json. Instead i get an error.

This is my Swift codeimport UIKit

let url = URL(string: "http://192.168.0.24:8080/login")!

var request = URLRequest(url: url)

request.httpMethod = "POST"

let param = ["username": "admin", "password": "admin"]

request.httpBody = try JSONSerialization.data(withJSONObject: param, options: [])

let session = URLSession.shared

session.dataTask(with: request) { (data, responce, error) in
    print(String(data: data!, encoding: .utf8)!)
}.resume()

Also here is the snippet of my python code

from flask import Flask, request
from userManagement import userManagement
import json

app = Flask(__name__)

x = {
    "name": "admin",
    "username": "admin",
    "password": "admin"
}
script = json.dumps(x)


@app.route("/")
def home():
    return "Home page"

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return "GET requested"
    elif request.method == "POST":
        #checking = userManagement().loginCheck(request.data)
        #return checking

        print(json.dumps(request.data))
        return "HI"
    else:
        return "Invalid"


if __name__ == "__main__":
    app.run(host="192.168.0.24", port="8080", debug=True)

From what i can see the issue originates from:

print(json.dumps(request.data))

however i am unsure on how i could fix this as i don't know how the process works on either swift or python.

James
  • 53
  • 1
  • 7
  • Does this answer your question? [How to get POSTed JSON in Flask?](https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask) – quamrana Aug 30 '20 at 07:04

1 Answers1

0

The problem here is with your swift post code rather than the python's flask code. Json dumps mostly throws an error during non-integral data structures conversion. Alternatively you could try using flasksjsonify to print the json dump. You can also use postman to publish a push request.

Javin
  • 124
  • 5