flask python tutorial with news API – Quick guide for beginners

python flask tutorial

Flask is a microframework for web development in python. In this flask python tutorial, you will know how to build a simple flask app with templates and API data.

For web development in python, we have the most popular frameworks Django and Flask and many others. In flask, we can customize more things like backend validations and security issues.

Check out the documentation for flask here

Requirements for flask python project

To start flask, first, we need to install flask on our computer. Installing python flask is damn easy. copy the code below and paste it on your prompt.

pip install flask

For this python flask project, we use google news API. news API provides only the data of news. we can use this data to build our project. we need to take permission from google. It is very easy. just log in through your Gmail.

we can directly work with API or we can use another news API package, this can simplify our work. Thanks, mattlisiv/newsapi-python

pip install newsapi-python

That’ s it guys, we don’t need anything else regarding the project. let’s learn some basics of python flask.

Basics of Python flask

open your favorite code editor and write this code.

1. Run your first app

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "we are in DevPyJp"

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

save this file as app.py. Now run this file using the below command on your prompt.

py app.py

copy that URL: http://127.0.0.1:5000/ on your prompt on your web browser. you definitely get the output as “we are in DevPyJp”.

2. Templates in flask python

we display the text in the last execution, but we need stylings and also we need to show large data on webpages. so we need templates to display images and data properly. let’s configure the templates to python flask.

create a new folder called “templates”. This folder holds all our HTML files of the project. let’s create an index.html file inside the template folder. write the code below in your index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>News APP</title>
</head>
<body>
    <h1> Hello world</h1>

 </body>
</html>

and in the app.py file, write the below lines.

from flask import Flask,render_template #import render_template

app = Flask(__name__)


@app.route('/')
def home():  
    return render_template('index.html') #here we are rendering our template file.


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

3. Display the variables in templates

we know the HTML files are static files, but always send dynamic data to web pages according to the user requirements. let’s crack that also.

@app.route('/')
def home():  
    website = 'www.devpyjp.com'

    return render_template('index.html',website = website) #we are defining the context here
<body>
    <h1> welcome to {{website}}</h1>

 </body>

Now run your script and see the output as “welcome to www.devpyjp.com”.

I hope you guys you must understand the basics of the flask python. I know you are excited to start with API, ok let’s start that also.

chek out my best articles here: Blog

Python flask project with news API

Make sure you must have the google news API key. please find it when you signup with your email here google news API

Here I am giving you the entire project code, take a look at that and I will explain to you each and every line in that.

app.py

from flask import Flask,render_template,request
from newsapi import NewsApiClient


app = Flask(__name__)

yourAPIKEY = ''   # write your API key here

newsapi = NewsApiClient(api_key=yourAPIKEY)


#print(top_headlines['articles'])

#head_lines=[]

#for news in top_headlines['articles']:
 #   head_lines.append(news['title'])


@app.route('/')
def home():
    #news =head_lines
    return render_template('index.html',news='')


    
@app.route('/results/',methods=['POST']) 
def get_results():
    keyword = request.form['keyword']  #getting input from user

    news = newsapi.get_top_headlines(q=keyword,
                                     #sources='bbc-news,the-verge',#optional and you can change
                                     #category='business', #optional and you can change also
                                     language='en', #optional and you can change also
                                     country='in')
    #print(news['articles'])
    return render_template('index.html',news=news['articles'])



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

get_results(): Take the searched keyword from user input and retrieve the results from API and sent back to template index.html.

q: It is used to search a keyword in google and finds the headlines. Eg: q=’ India’

sources: used for gathering news form different news websites like BBC, Times of India and many more.

category: you can specify which category news do you need here.

language: we can specify the language also.

country: you can specify your country name also, here I specified India. so the country code is “in”.

Note: check this link for all other options like country codes, languages, sources and category here https://newsapi.org/docs/endpoints/sources

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>News APP</title>
</head>
<body>
    <h1> Hello world
    </h1>

    <form action='/results/' method="POST">
        <input type="text" placeholder="Enter a search term" name='keyword'>
        <button type="submit">Get News</button>


    </form>


{% for post in news %}
  <h2>{{post['title']}}</h2>
  <i>{{post['publishedAt']}}</i>
  <p>{{post['description']}}</p>
{% endfor %}
   
    
</body>
</html>

If you followed my points then you will get the output like below. if you don’t please recheck, still getting any other errors please comment below, I will help you.

Output

I hope you definitely like this flask python tutorial, please appreciate us and also subscribe to our newsletter to notify you with our latest articles.

4 thoughts on “flask python tutorial with news API – Quick guide for beginners”

    1. That means you are not defined or assigned as a keyword in your program. please recheck your code. Thank you.

Leave a Reply