1

I am currently trying to integrate this free to use 3rd Party API into my website. I am using Python which uses flask so I will be using render templates so how do I pass this data through my to my template?

below is the method within my .py class which also has requests packaged installed. NOTE: I have used an invalid API key just for security measures.

@app.route('/Api', methods=['POST'])
def index():

    # BBC news api 
    main_url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=123"

    # fetching data in json format 
    open_bbc_page = requests.get(main_url).json() 

    # getting all articles in a string article 
    article = open_bbc_page["articles"] 

    # empty list which will  
    # contain all trending news 
    results = [] 

    for ar in article: 
        results.append(ar["title"]) 

    for i in range(len(results)): 

        # printing all trending news 
        print(i + 1, results[i])                  

return render_template('home_page.html')

if __name__ == '__main__':
    app.run(debug=True)

Also how do I then display this in my html file?

2 Answers 2

1

The render_template method takes **context parameters after the first parameter, which are variables that are to be made available in the context of the template. For example,

return render_template('home_page.html', results=results)

You can parse the response you receive from the requests however you'd like.

If you're returning a list, you can iterate through the list in the template with something like:

{% for result in results %}
    <p>{{result}}</p>
{% endfor %}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi , thank for the response. I currently new to python. i've tried this in my .py return render_template('home_page.html', display=results) however it does not pass anything to html using <p>{{display}}</p>
thanks, I have tried your example. I have pasted this loop into my html page however it does not return anything? could there be something wrong with my python code?
I can now confirm that it was my python code that was the issue, however this does answer my question. Thanks
0

Pass the articles variable into your template.

return render_template('home_page.html, articles = articles )’

Then run your for loops in your template. Ex:

 {%for ar in articles%}

Do stuff

{%endfor%}

1 Comment

Hi, Wes the question above as the same similar answer however I have tried your way still the same issue. Displaying nothing? would it be my python code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.