Discover how to build a robust directory service with Lovable. Follow our step-by-step guide for setup, best practices, and expert tips for success.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Creating a New Lovable Project
Configuring Dependencies via Code
lovable.json
in the root of your project.lovable.json
to specify that your project depends on Flask:
{
"dependencies": {
"Flask": "2.0.3"
}
}
Creating the Main Server File
main.py
in your project’s root directory. This file will host your server logic.main.py
:
from flask import Flask, jsonify, request
from directory import Directory
app = Flask(name)
directory = Directory()
Endpoint to list all contacts in the directory
@app.route('/directory', methods=['GET'])
def get_directory():
return jsonify(directory.get_all_contacts())
Endpoint to add a new contact to the directory
@app.route('/directory', methods=['POST'])
def add_contact():
contact = request.get_json()
directory.add_contact(contact)
return jsonify({'message': 'Contact added successfully!'}), 201
if name == "main":
# Lovable will run this file as the entry point; it listens on all IPs using port 8080.
app.run(host="0.0.0.0", port=8080)
Creating the Directory Module
directory.py
in the project’s root folder. This module will contain the logic for managing directory contacts.directory.py
:
class Directory:
def **init**(self):
# Using a simple list to store contacts in memory
self.contacts = []
def get_all_contacts(self):
return self.contacts
def add\_contact(self, contact):
# Append the contact (a dictionary with contact details) to the contacts list.
self.contacts.append(contact)
</code></pre>
</li>
Configuring and Running Your Directory Service App
lovable.json
, main.py
, and directory.py
) are saved in your project’s root directory.lovable.json
configuration and loads Flask as specified.main.py
; when you click the Run button in Lovable, the web server will start listening on port 8080
.
Testing and Interacting with Your Directory Service
/directory
in your browser; an empty list should be returned initially./directory
with a JSON payload.main.py
that sends a POST request when your app starts, then remove it once you have verified functionality.
Updating and Maintaining Your Directory Service
main.py
or directory.py
).lovable.json
configuration, any changes to dependency versions can be made there.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/directory', { useNewUrlParser: true, useUnifiedTopology: true });
const DirectorySchema = new mongoose.Schema({
name: { type: String, required: true },
category: { type: String, required: true },
location: { type: String, required: true },
lovableScore: { type: Number, default: 0 },
contact: {
email: { type: String },
phone: { type: String }
},
metadata: { type: mongoose.Schema.Types.Mixed }
});
const Directory = mongoose.model('Directory', DirectorySchema);
const app = express();
app.use(bodyParser.json());
app.post('/api/directory', async (req, res) => {
try {
const entry = new Directory(req.body);
await entry.save();
res.status(201).json(entry);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
app.get('/api/directory/top', async (req, res) => {
try {
const { category, location } = req.query;
const matchFilter = {};
if (category) matchFilter.category = category;
if (location) matchFilter.location = location;
const topEntries = await Directory.aggregate([
{ $match: matchFilter },
{ $sort: { lovableScore: -1 } },
{ $limit: 10 }
]);
res.json(topEntries);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Directory service running on port ${PORT}`);
});
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
// Endpoint to retrieve a directory entry enriched by data from an external Lovable API
app.get('/api/directory/:id/lovable', async (req, res) => {
try {
const { id } = req.params;
// Simulate a local directory entry retrieval (in a real scenario, fetch from your database)
const localEntry = {
id,
name: 'Artisan Cafe',
category: 'Food & Beverage',
location: 'Downtown'
};
// Connect to external Lovable API service to fetch detailed lovable metrics
const externalApiUrl = `https://api.lovableinfo.com/ratings/${id}`;
const externalResponse = await axios.get(externalApiUrl, { timeout: 5000 });
const externalData = externalResponse.data;
// Combine local and external data into a cohesive entry
const enrichedEntry = {
...localEntry,
lovableRating: externalData.rating,
reviews: externalData.reviews
};
res.json(enrichedEntry);
} catch (error) {
res.status(500).json({ message: 'Error fetching external data', details: error.message });
}
});
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => console.log(`Service running on port ${PORT}`));
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLFloat, GraphQLID } = require('graphql');
const axios = require('axios');
const memoryCache = new Map();
const fetchLovableData = async (id) => {
if (memoryCache.has(id)) {
return memoryCache.get(id);
}
const res = await axios.get(`https://api.lovableinfo.com/ratings/${id}`, { timeout: 5000 });
const data = res.data;
memoryCache.set(id, data);
return data;
};
const directoryData = {
"1": { id: "1", name: "Sunrise Bakery", category: "Food & Beverage", location: "Midtown" },
"2": { id: "2", name: "Urban Studio", category: "Art & Design", location: "Downtown" }
};
const DirectoryType = new GraphQLObjectType({
name: "Directory",
fields: {
id: { type: GraphQLID },
name: { type: GraphQLString },
category: { type: GraphQLString },
location: { type: GraphQLString },
lovableRating: {
type: GraphQLFloat,
resolve: async (parent) => {
const external = await fetchLovableData(parent.id);
return external.rating;
}
},
reviewCount: {
type: GraphQLString,
resolve: async (parent) => {
const external = await fetchLovableData(parent.id);
return external.reviews ? external.reviews.length.toString() : "0";
}
}
}
});
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
directory: {
type: DirectoryType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return directoryData[args.id];
}
}
}
});
const schema = new GraphQLSchema({
query: RootQuery
});
const app = express();
app.use("/graphql", graphqlHTTP({
schema,
graphiql: true
}));
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`GraphQL service running on port ${PORT}`));
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Prerequisites
Planning Your Directory Service
Designing the Architecture
Setting Up the Development Environment
Initializing a Sample Project
app.py
) for your back-end logic.from flask import Flask, request, jsonify
app = Flask(name)
@app.route('/')
def home():
return "Directory Service Home"
if name == 'main':
app.run(host="0.0.0.0", port=8080)
requirements.txt
file to list your project dependencies. For example:Flask
Add any other dependencies as necessary
</code></pre>
</li>
Integrating an AI Code Generator
# Generate a function that returns a JSON of all directory entries from the database
def get_directory_entries():
# Your AI tool can help fill in the logic here
pass
Implementing Directory Service Functionality
@app.route('/entries', methods=['GET'])
def list\_entries():
# In a real app, fetch data from a database
entries = [
{"name": "Business One", "location": "City A"},
{"name": "Business Two", "location": "City B"}
]
return jsonify(entries)
 >
Testing and Optimization
Deployment and Security
Monitoring and Maintenance
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.