DEV Community

Cover image for New Api application that I created

Posted on

New Api application that I created

Hello everyone I am so proud that I just finished my new api application and publish it on RapidAPI The application is to get calories and joules values in some foods data.

So I want to share my story with building this app with you I hope it will help or make some difference in your learning path.

1-First Step:

I started by searching for data source that I can be use it as database to get information from it in my app so I found a csv file on kaggle contains the data that I need.

2-Handling data source file:

Next step was convert the data in the csv file to mongo database so I used pymongo but before I pushed it to the database I created to the system to handling the informations that contains tow main types
Category and Food.

import uuid
from abc import ABCMeta, abstractmethod, ABC
from database import Database

class Model(metaclass=ABCMeta):
    collection = "model"

    def __init__(self, _id=''):
        self._id = _id or uuid.uuid4().hex

    def to_json(self):
        raise NotImplementedError

    def all(cls):
        return [cls(**item) for item in Database.all(cls.collection)]

    def save_to_db(self):
        Database.insert_one(self.collection, self.to_json())

    def fine_one_by_id(cls, _id):
        item = Database.find_one_by_id(cls.collection, _id)
        return cls(**item)

    def fine_one_by_name(cls, name):
        item = Database.find_one_by_name(cls.collection, name)
        return cls(**item)

    def delete_one(cls, _id):
        if cls.fine_one_by_id(_id):
            Database.delete_one(cls.collection, _id)

    def filter(cls, **kwargs):
        return [cls(**item) for item in Database.filter(cls.collection, **kwargs)]

class Category(Model, ABC):
    collection = "food_category"

    def __init__(self, name='', *args, **kwargs):
        super().__init__(*args, **kwargs) = name

    def to_json(self):
        return {
            '_id': self._id,

class Food(Model, ABC):
    collection = "food"

    def __init__(self, name='', per100grams=0, cals_per100grams=0, kj_per100grams=0, category_id='', *args, **kwargs):
        super().__init__(*args, **kwargs) = name
        self.per100grams = per100grams
        self.cals_per100grams = cals_per100grams
        self.kj_per100grams = kj_per100grams
        self.category_id = category_id

    def to_json(self):
        return {
            '_id': self._id,
            'per100grams': self.per100grams,
            'cals_per100grams': self.cals_per100grams,
            'kj_per100grams': self.kj_per100grams,
            'category_id': self.category_id

Enter fullscreen mode Exit fullscreen mode

3-Create file:

I created file to handle database functions it's contains Database class

from pymongo import MongoClient

class Database:
    url = "url_to_mongo_db"
    client = MongoClient(url)
    db = client.get_database()

    def insert_one(cls, collection, item):

    def find_one_by_id(cls, collection, _id):
        return cls.db[collection].find_one({'_id': _id})

    def find_one_by_name(cls, collection, name):
        return cls.db[collection].find_one({'name': name})

    def delete_one(cls, collection, _id):
        cls.db[collection].delete_one({'_id': _id})

    def all(cls, collection):
        return cls.db[collection].find({})

    def filter(cls, collection, **kwargs):
        return cls.db[collection].find(kwargs)

Enter fullscreen mode Exit fullscreen mode

after it I inserted all data from csv file to mongo database

4-Build api using flask

I used flask to create the app endpoints and tested it by postman software so every end point I created I test it

from flask import Flask, make_response, jsonify

from models import Category, Food

app = Flask(__name__)

def index():

def categories():
    all_categories = [category.to_json() for category in Category.all()]
    return make_response(jsonify(all_categories))

def get_category_by_name(category_name):
    selected_category = Category.fine_one_by_name(category_name)
    return make_response(jsonify(selected_category.to_json()))

def get_foods_by_category_name(category_name):
    selected_category = Category.fine_one_by_name(category_name)
    selected_foods = [food.to_json() for food in Food.filter(category_id=selected_category._id)]
    return make_response(jsonify({'category': selected_category.to_json(), 'foods': selected_foods}))

def foods():
    all_foods = [food.to_json() for food in Food.all()]
    return make_response(jsonify(all_foods))

def get_food_by_name(food_name):
    selected_food = Food.fine_one_by_name(food_name)
    return make_response(jsonify(selected_food.to_json()))

def sort_food_by_kj():
    selected_food = [food for food in Food.all()]
    selected_food.sort(key=lambda food: food.kj_per100grams)
    sorted_foods = [food.to_json() for food in selected_food]
    return make_response(jsonify(sorted_foods))

def sort_food_by_cals():
    selected_food = [food for food in Food.all()]
    selected_food.sort(key=lambda food: food.cals_per100grams)
    sorted_foods = [food.to_json() for food in selected_food]
    return make_response(jsonify(sorted_foods))

if __name__ == '__main__':

Enter fullscreen mode Exit fullscreen mode

5-Deploy app to heroku platform

after testing app endpoints I started preparing app to deploy it to heroku site first instaled gunicorn package the created requirements.txt by typing pip freeze>requirements.txt
then created app on heroku named it calories-app
and by following steps in heroku documentations finally deployed and has been live.

6-Publish app on RapidAPI:

after creating account on Rapiedapi I created new api app and after some steps I the app is done.

You can use it Now on foods-caloris

Please support me on my network links:

Discussion (0)