Introduction
I recently deployed my first Javascript REST API that returns facts about dogs. The impetus behind creating this project was to get a working front end solution with the API providing the data. While working on the front end, I started making use of the python API by DukeNgn that can be found here and ran into CORs issues that prevented me from getting the data.
Development
My main goal was to get the API deployed as quickly as possible and therefore, relied on the simplest solution making use of Express
and the Javascript fs
library to read a JSON file with all the facts. I also used the cors
javascript library to make sure I wouldn't run into the same issue as the python library:
// App config.
const app = express();
app.use(express.json());
app.use(Cors());
All the code is available here.
Deployment with Heroku
The deployment to Heroku was smooth following this tutorial. The only issue I got into was hardcoding a port that wasn't agreeable with Heroku for which configuring the listening port accordingly did the trick:
const port = process.env.PORT || 5000;
One of the coolest Heroku features was to hook up my GitHub repository to Heroku resulting in an automatic deployment whenever I pushed changes.
Usage
- https://dogfacts-api.herokuapp.com/api/v1/resources/dogs for all the dog facts.
- https://dogfacts-api.herokuapp.com/api/v1/resources/dogs?number={number} for a particular number of random dog facts.
- https://dogfacts-api.herokuapp.com/api/v1/resources/dogs?index={index} for a dog fact associated with the index - there are 435 total facts.
Example
https://dogfacts-api.herokuapp.com/api/v1/resources/dogs?number=2
Output:
[
{"fact":"Dogs are direct descendants of wolves."},
{"fact":"Small quantities of grapes and raisins can cause renal failure in dogs. Chocolate, macadamia nuts, cooked onions, or anything with caffeine can also be harmful."}
]
Conclusion
Building the API was an awesome learning experience! Any feedback about the code or this blogpost would be greatly appreciated.
Top comments (2)
Great Job
Very cool project! I never heard of Heroku, until now. You inspired me to create a simple API aswell Link to My API. Deploying with heroku was indeed very smooth. It has a very clear documentation. Thank you for sharing this!
Thank you very much for the appreciation! Your API is awesome - the code is extremely clean and was an easy read. Look forward to seeing more of your posts!
Best,
M.