Bootstrap FreeKB - Flask - Submitting a GET request to an API
Flask - Submitting a GET 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
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

requests can be used to submit a GET request to an API. First you will need to install requests.

pip install requests

 

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

import requests

@views.route('/test')
def test():
    response = requests.get("http://api.example.com/api")
    print("response      = " + str(response))
    print("response.text = " + str(response.text))
    print("response.json = " + str(response.json()))
    print("name          = " + str(response.json()['foo']))
    return render_template('bar.html')

 

Which should print something like this.

response = <Response [200]>
response.text = {"foo": "hello world"}
reponse.json  = {'foo': 'hello world'}
foo           = hello world

 




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 aedd4d in the box below so that we can be sure you are a human.