In this post, you will see code samples for a function to get local news in a nodejs, express & Typescript API. Towards the end of this post, you will also see the link to a Github repository for the entire nodejs, typescript project for this API.
</newscatcher>
There are several third party vendor based news APIs but this was chosen due to the ease of obtaining a key and the free 30 days trial period. If you know of another news source or an API, then please leave a comment or send a message.
Local news in Nodejs, express & Typescript
For the purpose of this project, you will be using the axios library for your asynchronous API calls.
import axios from "axios";
import { Request, Response } from "express";
//newscatcher API
export function getNews(request: Request, response: Response) {
const API_KEY = process.env.NEWS_CATCHER_KEY;
const searchTerms = "Sydney Weather Properties";
const newsCatcherUrl = `https://api.newscatcherapi.com/v2/search?q=${searchTerms}`;
axios.get(newsCatcherUrl, {
headers: {
'x-api-key':`${API_KEY}`
}
})
.then(result => {
response.json(result.data).status(200);
})
.catch(err => {
response.send(JSON.stringify(err));
response.json(err.message).status(err.status);
});
}
The code above is fairly straightforward, however listed below is an explanation for it.
- Initialise the API key with the value from the environment (.env) file from the nodenv
- Define the search terms (it can be anything you want)
- Declare the newscatcher api url
- Use the axios.get method to call the newscatcher API and parse the response in a then block
Conclusion
Hope you found this blogpost useful and you can find the full source code for this repo here on Github which also has instructions to setup and run this repo. You can obtain a newscatcher API key from here.
If you find any of my posts useful and want to support me, you can buy me a coffee 🙂
https://www.buymeacoffee.com/bhumansoni
While you are here, maybe try one of my apps for the iPhone.
Products – My Day To-Do (mydaytodo.com)
Have a read of some of my other posts on AWS
Deploy NodeJS, Typescript app on AWS Elastic beanstalk – (mydaytodo.com)
How to deploy spring boot app to AWS & serve via https – My Day To-Do (mydaytodo.com)
Some of my other posts on Javascript …
What is Javascript event loop? – My Day To-Do (mydaytodo.com)
How to build a game using Vanilla Javascript – My Day To-Do (mydaytodo.com)
Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)
Java Spring Boot & Vanilla Javascript solution – My Day To-Do (mydaytodo.com)
Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)
0 Comments