Home > Software design >  How to convert strings from HTML request to Python objects with FastAPI
How to convert strings from HTML request to Python objects with FastAPI

Time:10-16

I am making my first API; any advice to improve my process is much appreciated.

I plan on passing JSON-like strings into the HTML request to this FastAPI microservice down there

@app.get("/create/{value}")
def createJSON(value:str):
    person_json = value.strip()
    fileName = person_json['Value']['0']   person_json['Value']['1']
    with open('%s.JSON','w') as writeFile:
        writeFile.write(string)
        return "Person has been created"

My HTTP request would look like this:

http://127.0.0.1:8000/create/{"Key":{"0":"name","1":"grad_year","2":"major","3":"quarter","4":"pronoun","5":"hobbies","6":"fun_fact","7":"food","8":"clubs","9":"res"},"Value":{"0":"adfasdfa","1":"adf'asd","2":"asd","3":"fads","4":"fa","5":"sdfa","6":"df","7":"asd","8":"fa","9":"df"}}

However, when doing this. The values passed are strings. Thus rendering the fileName portion of the code useless. How can I convert it to a Python dict? I have tried to use .strip(), but it did not help.

CodePudding user response:

You're on the wrong track, Such a request should be essentially modeled as POST or a PUT request. That would allow you to send JSON in the body of the request and obtain it as a dict in python. You can see here

And even if you want to pass data in a GET request, there are query params

Coming back to the original doubt, you would have to use json.loads() to parse the json data and load it in a python dict then you can dump whatever file you like after that.

CodePudding user response:

I'd recommend using the requests library

import requests

url = 'http://127.0.0.1:8000/create/'

params = dict(
   name = 'Josh',
   grad_year = '1987',
   major = 'computer science',
   quarter = '3'
)

resp = requests.get(url=url, params=params)
data = resp.json()
   

Then see here how to handle the JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content

The dict in the code I posted is different than the JSON you're trying to send through though. I assume you have a specific reason for having a "Key" array with the names than a "Value" array for the values of those specific names. But if not I'd recommend using a dictionary instead that way you can do things like:

fileName = person_json['name']   person_json['grad-year']
  • Related