Build a Simple News App Using Django and News API

In this article I will show you how you can build a simple news app using Django and News API. This project is quite simple, and will be a great starting point for newbie Python/Django developers.

What Will the App Do?

This app will use News API to display the latest news on the topic of your choice. We will use Django to display the news headline and a short description. Users will be able to click on the headline to read the story in full. Upon successful completion, you will have a cool web app that looks like this.

image.png

Setting up Your Project

It is always best practice to build you Django projects in a virtual environment. If you're not familiar with virtual environments check out this guide. For the IDE I will be using PyCharm but any other you're comfortable with is still fine. Create a folder in your PC where your project files will be stored. Open your IDE and navigate to the folder via Files->Open.

Run the following commands in your IDE’s terminal to set up and activate your virtual environment:

python -m venv env
env\Scripts\activate

Now, what we need to do next is install the prerequisites needed for this project. We will need to install Django and the News API package.

pip install django
pip install newsapi-python

After successful installation of Django and the News API package it is time to create our project. To create the project run the following command. Remember to add the . at the end.

django-admin startproject news .

Now let's create your Django application. You will create a news application from scratch. From the project's root directory, run the following command:

python manage.py startapp newsapp

Start the local server by running:

python manage.py runserver

Now open http://127.0.0.1:8000/ in your browser. You should see a page stating that the project is successfully running.

Using News API

You will need to sign up for an account on the News API website for you to get an API key. Make sure you keep the API key private. The key will help you retrieve data from News API. At this point, we are now ready to move on to the next step which is fetching news.

Go to the newapp directory and open the views.py file.

A Django view is a Python function that receives a web request and returns a web response. The code required to return the desired response goes inside the view. In the views.py file add the following code:

#importing the required libraries
from newsapi import NewsApiClient
from django.shortcuts import render

# Create your views here.
def homepage(requests):
    newsapi = NewsApiClient(api_key='API_KEY')
    trending = newsapi.get_top_headlines(country='gb', category='sports')
    latest = trending['articles']
    headline = []
    description = []
    url = []
    author = []
    date = []

    for i in range(len(latest)):
        news = latest[i]
        headline.append(news['title'])
        description.append(news['description'])
        url.append(news['url'])
        author.append(news['author'])
        date.append(news['publishedAt'])

    zipped_news = zip(headline, description, url, author, date)

    context = {
        'zipped_news': zipped_news
    }

    return render(requests, 'home.html', context=context)
  • At the top we import the required libraries.

  • Next, we create a Python function called homepage -you can use a different name- that takes in requests and renders a HTML template. Under the function, we will fetch the top sports headlines trending in the UK using:

newsapi.get_top_headlines(country='gb', category='sports')

Use this documentation from News API if you would like to fetch different news. Basically, all you need to do is change the arguments.

Creating a HTML Template

Templates define how the data is displayed; they are usually written in HTML alongside the Django template language. Create a templates folder in your project’s directory. Inside the templates folder create a HTML file and name it index.html.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>My Sports Website</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    </head>
    <body>
        <div class="jumbotron" style="color:black">
         <h1 style ="color:white">Get The Latest Sports News</h1>
        </div>

        <div class="container">
            {% for headline, description, url, author, date in zipped_news %}

                <a href="{{ url }}">
                <h2 class="post-title">{{ headline }}</h2>
                <h3 class="post-subtitle">{{ description }}</h3>
                </a>
                <p>Posted by <a href="#">{{ author }}</a> on {{ date }}</p>

            <!-- Divider-->

            {% endfor %}

        </div>
    </body>    
</html>

You can customize the HTML further add more styling later on. However, this will be enough to get you started if you're not well versed with HTML.

Let’s Route Our Views

Last, we need to route the views. URL patterns allow you to map URLs to views. A URL pattern includes: a string pattern, a view, and, optionally, a name. Head over to the urls.py located within your project folder and add the following code.

from django.contrib import admin
from django.urls import path
from newsapp import views

urlpatterns = [
path('', views.homepage, name ='index'),
    path('admin/', admin.site.urls),
]

You’ve now successfully created a simple News App using Django and News API. You can customize the parameters inside your view to fetch different types of articles. Happy coding. The code for this project is available on my GitHub .