JSON To REST Endpoint

Read a JSON file and provide its data as a REST endpoint. That can be helpful in some projects for testing.

from fastapi import FastAPI
import json

app = FastAPI()

def get_json_data():
  with open('erp_customers.json') as f:
    data = f.read()
  return json.loads(data)

def get_customers(data, query):
  if query.startswith('~/', 0, 2):
    erp_data_objects = [x for x in data['content']['data']['erpDataObjects'] if query.lower()[2:] in x['head']['fields']['ans']['value'].lower()]
  else:
    erp_data_objects = [x for x in data['content']['data']['erpDataObjects'] if query.lower() == x['head']['fields']['ans']['value'].lower()]
  data['content']['data']['erpDataObjects'] = erp_data_objects
  return data

@app.get("/mw/r/erp/obj/data/{dataid}")
def read_customer(dataid: int, headFields: str, criteria: str):
  return get_customers(data=get_json_data(), query=criteria)

For listening on requests we utilize uvicorn.

$ uvicorn main:app --reload
INFO:
Will watch for changes in these directories: ['/home/user/Projects/test_rest_endpoint']
INFO:
Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:
Started reloader process [1316803] using StatReload
INFO:
Started server process [1316805]
INFO:
Waiting for application startup.
INFO:
Application startup complete.

Reach out to me for professional support!

Contact