DEV Community

Cover image for New Api application that I created
Mert
Mert

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

    @abstractmethod
    def to_json(self):
        raise NotImplementedError

    @classmethod
    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())

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

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

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

    @classmethod
    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)
        self.name = name
        pass

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


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)
        self.name = name
        self.per100grams = per100grams
        self.cals_per100grams = cals_per100grams
        self.kj_per100grams = kj_per100grams
        self.category_id = category_id
        pass

    def to_json(self):
        return {
            '_id': self._id,
            'name': self.name,
            '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 database.py 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()

    @classmethod
    def insert_one(cls, collection, item):
        cls.db[collection].insert_one(item)
        pass

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

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

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

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

    @classmethod
    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__)


@app.route('/')
def index():
    return 'WELCOME TO FOOD CALORIES API'


@app.route('/categories/all')
def categories():
    all_categories = [category.to_json() for category in Category.all()]
    return make_response(jsonify(all_categories))


@app.route('/categories/<category_name>')
def get_category_by_name(category_name):
    selected_category = Category.fine_one_by_name(category_name)
    return make_response(jsonify(selected_category.to_json()))


@app.route('/categories/<category_name>/foods')
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}))


@app.route('/foods/all')
def foods():
    all_foods = [food.to_json() for food in Food.all()]
    return make_response(jsonify(all_foods))


@app.route('/foods/<food_name>')
def get_food_by_name(food_name):
    selected_food = Food.fine_one_by_name(food_name)
    return make_response(jsonify(selected_food.to_json()))


@app.route('/foods/sorted-by-kj')
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))


@app.route('/foods/sorted-by-cals')
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__':
    app.run(debug=True)

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:
patreon
youtube
facebook
instagram

Top comments (1)

Collapse
 
ghe4w33 profile image
hjdrh sdfs

Korean caviar is known for its distinct flavor profile, which can vary depending on the type of fish and the processing methods used korea caviar. It is often described as creamy, buttery, and slightly salty. This unique taste makes it a sought-after ingredient in gourmet cuisine.