Juyal Ahmed
Juyal Ahmed

Reputation: 11

How to validate JSON request body before sending PUT request in python

It's when I send a PUT request to my API endpoint from python with a JSON request body I receive empty request body, because sometimes It's containing special characters which is not supported by JSON.

How can I sanitize my JSON before sending my request?

I've tried with stringify and parsing json before I sent my request!

profile = json.loads(json.dumps(profile))

My example invalid json is:

{
    "url": "https://www.example.com/edmund-chand/",
    "name": "Edmund Chand",
    "current_location": "FrankfurtAmMainArea,   Germany",
    "education": [],
    "skills": []
}

and My expected validated json should be:

{
    "url": "https://www.example.com/edmund-chand/",
    "name": "Edmund Chand",
    "current_location": "Frankfurt Am Main Area, Germany",
    "education": [],
    "skills": []
}

Upvotes: 1

Views: 3384

Answers (2)

Juyal Ahmed
Juyal Ahmed

Reputation: 11

Thank you @Rithin for your solution but that one seems more coupled with one field of the whole JSON.

I found a solution to replace it with below example code which works for any field:

profile = json.loads(json.dumps(profile).replace("\t", " "))

Upvotes: 0

Rithin Chalumuri
Rithin Chalumuri

Reputation: 1839

If you're looking for something quick to sanitize json data for limited fields i.e. current_location, you can try something like the following below:

def sanitize(profile):

    profile['current_location'] = ', '.join([val.strip() for val in profile['current_location'].split(',')])

    return profile

profile = sanitize(profile)

The idea here is that you would write code to sanitize each bits in that function and send it your api or throw exception if invalid etc.


For more robust validation, you can consider using jsonschema package. More details here.

With that package you can validate strings and json schema more flexibly.

Example taken from the package readme:

from jsonschema import validate

# A sample schema, like what we'd get from json.load()
schema = {
     "type" : "object",
     "properties" : {
        "url" : {"type" : "string", "format":"uri"},
        "current_location" : {"type" : "string", "maxLength":25, "pattern": "your_regex_pattern"},
     },
}

# If no exception is raised by validate(), the instance is valid.
validate(instance=profile, schema=schema)

You can find more infor and types of available validation for strings here.

Upvotes: 1

Related Questions