Skip to content

Instantly share code, notes, and snippets.

@balvinder294
Created January 18, 2022 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balvinder294/0011edfe5498d00a34b5ffce4f8a076f to your computer and use it in GitHub Desktop.
Save balvinder294/0011edfe5498d00a34b5ffce4f8a076f to your computer and use it in GitHub Desktop.
Sample script to Create api from falcon and manipulate json from a url response
#author @tekraze
import falcon
import requests
class Hello:
def on_get(self, req, resp):
# we just send back a string here
resp.media = 'hello'
class HelloJSON:
def on_get(self, req, resp):
# we just send back a string here
resp.media = {'greet': 'hello'}
class JSONfromURL:
def on_get(self, req, resp):
# here we get data from url and then send it back as a response
fakeUsersAPIUrl = 'https://jsonplaceholder.typicode.com/users'
usersRequest = requests.get(fakeUsersAPIUrl)
usersResponse = usersRequest.json()
usersRequest.close()
resp.media = usersResponse
class JSONfromURLChange:
def on_get(self, req, resp):
# here we get data from url and then send it back as a response
fakeUsersAPIUrl = 'https://jsonplaceholder.typicode.com/users'
usersRequest = requests.get(fakeUsersAPIUrl)
usersResponse = usersRequest.json()
usersRequest.close()
# here we additionally create new data and send back to show how manipulation works
# to hold new data
newDataArray = []
print(type(usersResponse))
for key in usersResponse[:10]: ## to just get n items instead of whole list
newData = {}
newData['serial'] = key['id']
newData['name'] = key['name']
newDataArray.append(newData)
resp.media = newDataArray
middle = falcon.CORSMiddleware(
allow_origins="*"
)
api = falcon.App(middleware=middle)
api.add_route('/greet', Hello())
api.add_route('/greet-json', HelloJSON())
api.add_route('/json-from-url', JSONfromURL())
api.add_route('/json-from-url-change', JSONfromURLChange())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment