-2

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • I have removed your "bonus" questions. A question on Stack Overflow should ask one question. – Mark Rotteveel Oct 16 '22 at 05:21
  • 1
    Please have a look at [this answer](https://stackoverflow.com/a/70636163/17865804), as well as [this](https://stackoverflow.com/a/71741617/17865804) and [this](https://stackoverflow.com/a/73761724/17865804) on how to post JSON data to FastAPI backend. Relevant documentation can be found [here](https://fastapi.tiangolo.com/tutorial/body/). – Chris Oct 16 '22 at 05:52

2 Answers2

1

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.

kannavkm
  • 79
  • 2
  • 9
0

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']