Bootstrap FreeKB - Flask - Submitting a POST request to an API
Flask - Submitting a POST request to an API

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your flask project has the following structure.

├── main.py
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html

 

requests can be used to submit a POST request to an API. pip install can be used to install requests.

pip install requests

 

In your view (views.py in this example), here is how you could submit a POST request to api.example.com/api. Check out my article Python - POST Request for more details on the Python side of this.

import requests

@views.route('/Test', methods=['GET', 'POST'])
def test():
    url      = "http://api.example.com/api/v1/example"
    data     = { "foo": "hello", "bar": "world" }
    headers  = { "Content-Type": "application/json" }
    response = requests.post(url, json=data, headers=headers)
    return str(response.json())

 

And here is how the API could process the POST request.

@views.route('/api/v1/example', methods=['GET', 'POST'])
def apiv1example():

    try:
        json = request.get_json()
    except Exception as exception:
        return {"result":"failed", "message": f"request.get_json() raised the following exception: {exception}"}
    
    try:
        json['foo']
    except KeyError as error:
        return {"result":"failed", "message": f"json['foo'] key raised KeyError {error}"}
    else:
        return {"result":"success", "message": f"json['foo'] = {json['foo']}"}  

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter dbcac8 in the box below so that we can be sure you are a human.