Home > OS >  How do I run a script when an api endpoint is hit?
How do I run a script when an api endpoint is hit?

Time:11-19

Here is how I want my program to work. Step 2 is what I am unsure of how to implement.

  1. Client makes API call to /email endpoint
  2. /email endpoint has a script run that gather emails from GMAIL API
  3. Put contents into response object
  4. Returns response object back to client

I understand how to make a static api response. But I can't get a python script to run when the api endpoint is hit.

CodePudding user response:

I saw the flask tag in your post.

I only played around with flask for certain interviews, but know enough to say calling a python script outside your running server is somewhat of an antipattern.

I assume your backend is a flask app, so ideally, you'd want to wrap whatever script you have in your python script file in a function and simply call it from your flask method when the endpoint is hit.

Something like:

from flask import Flask
from custom_emails_module import gather_email

@api.route('/email', methods=["GET"])
def method_associated_with_your_endpoint():
    # additional
    gather_email()

where custom_emails_module should be the module you create for your gather_emails script.

Now, at the end of your gather_emails function, simple remember to return the correct type, usually done with:

return json.dumps("success": True, "data": python_object_with_several_emails)

Use something like PostMan for local debugging and remember to use application/json in header for Content-Type.

Good luck!

  • Related