Prerequisites
To follow along with this tutorial, you should have basic knowledge of:
- Python and Django
- JavaScript
- HTML & CSS
- API Intergration
What We’ll Build
We’re building a Django-based app that allows users to search for financial news by entering keywords. The app will fetch results from the Bloomberg API and display them dynamically on the page.
By the end of the tutorial, you'll have a functional news search tool like this:
Step 1: Setting Up the Django Project
First, make sure you have Django installed. If not, you can install it by running:
pip install django
django-admin startproject news_finder cd news_finder python manage.py startapp search
search app to your INSTALLED_APPS in the settings.py file.INSTALLED_APPS = [
# Other apps
'search',
]Step 2: Integrating the Bloomberg API
We’ll be using the Bloomberg Market and Financial News API via the RapidAPI platform. First, sign up for RapidAPI and get your API key for Bloomberg News.
In your settings.py, add your Bloomberg API key as a sensitive variable:
BLOOMBERG_RAPID_API_KEY = "your_rapidapi_key_here
views.py:import requests
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
def fetch_bloomberg_news(keyword):
headers = {
"X-RapidAPI-Host": "bloomberg-market-and-financial-news.p.rapidapi.com",
"X-RapidAPI-Key": settings.BLOOMBERG_RAPID_API_KEY,
}
query_params = {"query": keyword}
url = "https://bloomberg-market-and-financial-news.p.rapidapi.com/market/auto-complete"
try:
response = requests.get(url, headers=headers, params=query_params)
response.raise_for_status()
data = response.json()
if len(data.get('news', [])) == 0:
return f'We\'ve got nothing on "{keyword}"', []
else:
return keyword, data['news'][:20]
except requests.exceptions.RequestException as e:
print(f"Error fetching Bloomberg news: {e}")
return "Failed to load news. Please try again later.", []This function accepts a search keyword, makes a request to the Bloomberg API, and returns the top 20 results if available.
Step 3: Creating the Search View
Next, we'll create a view that handles the search requests and returns the news data dynamically via AJAX.
Add the following function to views.py:
@csrf_exempt
def bloomberg_news_finder(request):
if request.method == 'POST':
keyword = request.POST.get('search_box', '').strip()
if keyword:
loading_text, news_items = fetch_bloomberg_news(keyword)
return JsonResponse({
'loading_text': loading_text,
'news_items': news_items
})
return render(request, 'bloomberg_news_finder.html', {})This view listens for POST requests from our form, fetches the news using the keyword, and returns a JSON response.
Step 4: Setting Up the HTML Template
Now let's create the template for our app. Create a new HTML file called bloomberg_news_finder.html in your templates directory.
<main class="container my-5 py-5 px-4">
<div class="row justify-content-center">
<div class="col-lg-6 col-sm-10">
<h1 class="text-center mb-3">Bloomberg News Finder</h1>
<form id="news-search-form" class="d-flex input-group">
<input id="search-box" name="search_box" class="form-control rounded-start" type="text" required placeholder="Search for the latest news in any topic..."/>
<button id="search-button" class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
<div id="news-list" class="row justify-content-center">
<div class="col-sm-12 col-lg-8">
<h4 id="loading-text" class="text-center text-muted fw-400 my-4"></h4>
<div class="list-group" id="news-items"></div>
</div>
</div>
</main>
<script>
document.getElementById("news-search-form").addEventListener("submit", function(event) {
event.preventDefault();
let searchBox = document.getElementById("search-box");
let keyword = searchBox.value.trim();
let newsList = document.getElementById("news-items");
let loadingText = document.getElementById("loading-text");
if (keyword === "") {
alert("Please enter a search keyword.");
return;
}
// Show loading text
loadingText.textContent = `Getting news for "${keyword}"...`;
newsList.innerHTML = ""; // Clear previous results
// Send AJAX request
fetch("{% url 'bloomberg_news_finder' %}", {
method: "POST",
headers: {
"X-CSRFToken": "{{ csrf_token }}",
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams({
search_box: keyword
})
})
.then(response => response.json())
.then(data => {
// Update loading text
loadingText.textContent = `Here's what we've got on "${data.loading_text}"`;
// Clear existing news
newsList.innerHTML = "";
// Display fetched news items
if (data.news_items.length > 0) {
data.news_items.forEach(post => {
let newsItem = document.createElement("a");
newsItem.classList.add("list-group-item", "list-group-item-action");
newsItem.href = post.longURL;
newsItem.target = "_blank";
let content = `
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">${post.title}</h5>
<small class="text-muted">${new Date(post.date * 1000).toLocaleDateString()}</small>
</div>
`;
newsItem.innerHTML = content;
newsList.appendChild(newsItem);
});
} else {
newsList.innerHTML = "<p class='text-center'>No news found.</p>";
}
})
.catch(error => {
console.error("Error fetching news:", error);
loadingText.textContent = "Error fetching news. Please try again later.";
});
});
</script>Step 5: Adding the URL Configuration
To tie everything together, add the following URL pattern to your urls.py:
from django.urls import path
from .views import bloomberg_news_finder
urlpatterns = [
path('', bloomberg_news_finder, name='bloomberg_news_finder'),
]Step 6: Running the App
Now that everything is in place, run the Django development server:
python manage.py runserver
Visit http://127.0.0.1:8000/ in your browser, and you should see the search interface for the Bloomberg News Finder. Enter a keyword like "Bitcoin," and the app will fetch the latest news articles from Bloomberg's API.
Conclusion
In this tutorial, we built a dynamic news search tool using Django and AJAX. We integrated the Bloomberg API to fetch real-time financial news and displayed it on our page without requiring a full page reload. This is just the start – you can further enhance the app by adding features like pagination, styling, or even integrating it with other news APIs.
I hope you found this guide helpful! Feel free to ask questions or share your version of the Bloomberg News Finder. Stay tuned for more tutorials!
Click here to try the app now