Flask - Submitting a GET request to an API
by
Jeremy Canfield |
Updated: May 25 2024
| 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(f"response = {response}")
print(f"response.text = {response.text}")
print(f"response.json = {response.json()}")
print(f"name = {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