0

I'm writing a simple flask-restful API and I need to insert some resource into database. I want to have hash id visible in the URL like this /api/resource/hSkR3V9aS rather than just simple auto-increment id /api/resource/34

My first thought was to use Hashids and just generate the hash_id from auto-increment id and store both values in the database, but the problem is that I would have to first INSERT new row of data, GET the id and then UPDATE the hash_id field.

Second attempt was to generate hash_id (e.g. sha1) not from id but some other field that I'm passing to databse and use it as a primary key (get rid of auto-inc id), but I fear that searching and comparing string each time rather than int will be much, much slower.

What is the best way to achive desired hash_id based URL along with acceptable speed of database SELECT queries?

I think this is the most related stack question, but it doesn't answer my question.

Major technology details: Python 3.6, flask_mysqldb library, MySQL database Please let me know if I ommited some information and I will provide it.

1 Answers1

1

I think I found a decent solution myself in this answer

Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.

It's per-connection based so there is no fear that I'll have 2 rows with the same ID.

I'll now use previously mentioned by myself Hashids and return hashed value to client. Hashids can be also decoded and I'll do it each time I get a request from url with this hash id included.

Also I found out that MongoDB database generates this kind of hashed id by itself, maybe this is a solution for someone else with similar problem.