``We can showcase API data using various endpoints and then present it on a web page using

Hello from Argentina! I'm new to programming and recently started a Flask project. I've successfully displayed information from an API using one endpoint and rendered it with Flask. However, I'm now facing the challenge of displaying information from multiple endpoints.

Below is the code I used to render the data, even though it may not be the cleanest:




def home():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
    oficial = requests.get('https://api-dolar-argentina.herokuapp.com/api/dolaroficial')
    blue = requests.get('https://api-dolar-argentina.herokuapp.com/api/dolarblue')
    dataoficial = json.loads(oficial.content)
    datablue = json.loads(blue.content)
    return render_template('home.html', posts=posts, data=dataoficial, datablue=datablue)




My next task involves working with multiple endpoints on the API. Below is a script that illustrates what I aim to achieve:





symbol = ['dolaroficial', 'dolarblue', 'contadoliqui', 'dolarpromedio', 'dolarturista','dolarbolsa']
for i in symbol:    
    api_url = f'https://api-dolar-argentina.herokuapp.com/api/{i}'
    data = requests.get(api_url).json()
    print(f' {i}: precio de venta', {data['venta']})
    print(f' {i}: precio de compra', {data['compra']})




I attempted to loop through all endpoints like the example above, but unfortunately, nothing was rendered:





def argentina():
    symbol = ['dolaroficial', 'dolarblue', 'contadoliqui', 'dolarpromedio', 'dolarturista', 'dolarbolsa']
    for i in symbol:
        api_url = f'https://api-dolar-argentina.herokuapp.com/api/{i}'
        datasa = requests.get(api_url)
        data = json.loads(datasa.content)

        return render_template('currency.html', data=data )


{% extends 'layout.html' %}
{% block content %}
<div>
    {% for dat in data %}
        {{ dat['compra'] }}
    {% endfor %}
</div>
{% endblock content %}

If I attempt to do this manually, the result won't look great. Can anyone guide me on how to display this information effectively? Thank you in advance and have a wonderful day!

Answer №1

The issue causing the API to respond with a 404 status is an extra space in the last item of symbol. Replace ' dolarbolsa' with 'dolarbolsa' to resolve the JSONDecodeError error (handling errors in the API is crucial).

To display multiple prices, you need to save the dollar price in an array instead of a variable and render the template after looping through each value in the array.

To implement this change, create a new array after defining symbol, populate it within the loop, and then render it once the loop completes.

def argentina():
  symbol = ['dolaroficial', 'dolarblue', 'contadoliqui', 'dolarpromedio', 'dolarturista', 'dolarbolsa']
  data = []
  
  for i in symbol:
    api_url = f'https://api-dolar-argentina.herokuapp.com/api/{i}'

    datasa = requests.get(api_url)
    content = json.loads(datasa.content)

    data.append(content)

  return render_template('currency.html', data=data)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining the value of a JSON object is not defined - utilizing jQuery's

It has been quite some time since I last dabbled in jQuery and I am currently facing a challenge extracting the value from the JSON returned by the server. C# approach [HttpGet] public JsonResult AjaxGetSingleNewsItem(int Id) { ...

How can Python script be used to import a sql.gz file into a MySQL database?

I have successfully exported a database using mysqldump in the sql.gz format with a python script. Now, I am looking for a way to import that sql.gz file using the same python script. The code I have currently written is capable of working with .sql or .t ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

What are the steps for invoking Google Vision's legacy models?

I am looking to utilize the older text_detection and document_text_detection model. (refer: https://cloud.google.com/vision/docs/service-announcements) I am attempting to do so using the features parameter: import io from google.cloud import vision ...

Error: 'BigList' does not have attribute 'reader'

Hey everyone, I'm currently learning how to code and working on a small script to read a CSV file. I keep getting an error that says "object has no attribute". Can someone please assist me with this? import csv class LargeList: def readCsv(self, ...

Locate all rows in Pandas where specific columns contain a certain text fragment

I am struggling to find rows in a DataFrame where 2 Columns contain a portion of a specified string s. The Column Values (Type String(Object)) I am looking for the opposite of str.contains or isin(), as the substring acts as the Column Value. The stri ...

Tips for choosing a numerical value received through the serial port

My motion sensor device sends data to me via a serial port. The data is organized in lines and always starts with a letter, like this: All the numbers are separated by commas, and each line ends with a '\r' character. I am specifically int ...

Creating POJOs by parsing two JSON files, with one file referencing the other

I currently have two JSON files named occupations.json and people.json. The first file contains an array of occupations: [ { "name": "developer", "salary": "90000"}, { "name": "designer", "salary": "80000"}, { "name": "manager", "salary": "700 ...

Spring Boot Ajax Parse Error - issue with returning object to Ajax success function

When I make a jQuery ajax call to my Spring controller, I am trying to send back an object to fill out a form in an iziModal. The data gets sent from the browser to the controller and runs through the method, but then I hit a roadblock. I'm having tro ...

Consolidating and organizing rows into one group

I am looking to combine and clean up some rows in order to consolidate them into one. Here is the dataset provided: customer flow session timestamp name recommends cpf delivery 0 C1000 F1000 S1000 2019-12-16 13:5 ...

What is the best way to add a hidden input inside an HTML button using Python Selenium?

I am currently utilizing Python to code in Selenium's WebDriver. Upon analyzing the HTML, I discovered that the 'submit' button I am attempting to click has a hidden ID input: <html><head> <title>Generating ID</title&g ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

I'm receiving an error message stating that the file cannot be loaded due to disabled script execution on this system. Can you

Currently facing an issue while loading a python file in PyCharm. There is a warning popping up which wasn't there before. Interestingly, print('Hello') function is working fine but I am encountering difficulties in installing Django. Encoun ...

How can I extract a nested class in Python using Selenium?

I am currently extracting data from a webpage and I want to retrieve information from a specific class that is nested inside another class. Here's my code snippet: x = browser.find_element_by_id("resposta-situacao-eleitoral") y = x.find_ele ...

How can I obtain the security token for Python SDK boto3?

I'm struggling to access the AWS Comprehend API from my Python script and can't seem to find a solution for this error. I know that obtaining a session security token is crucial, but beyond that, I'm stuck. try: client = boto3.client(serv ...

When attempting to import the image path from a JSON file, a ReferenceError occurs stating that the data variable is not

I'm currently attempting to iterate through image paths in a JSON file and display them in a browser using the "img" tag. While hardcoded values work perfectly fine, I encountered an issue when trying to switch to a variable as outlined in this post: ...

How can Angular incorporate JSON array values into the current scope?

I am currently working on pushing JSON data into the scope to add to a list without reloading the page. I am using the Ionic framework and infinite scroll feature. Can someone please point out what I am doing wrong and help me figure out how to append new ...

What are the signs of a syntax error in a jQuery event like the one shown below?

One of my forms has an ID attribute of id ='login-form' $('#login-form').submit(function(evt) { $('#login-button').addClass('disabled').val('Please wait...'); evt.preventDefault(); var postData = ...

What is the purpose of Python creating a JSON file from a string?

I am trying to create a json file by combining data from an api request and another json file. However, I am facing issues with the generated json file as it contains double quotes around the braces and escape characters like "\n" and "\r" scatte ...

Is it necessary to call the constructor after parsing JSON objects?

Check out this POJO class designed for a JSON object: public class JSONChangeSet { public JSONChangeSet { System.out.println("Owner: " + owner); } @SerializedName("comment") private String comment; @SerializedName("lastUpdate ...