If you’ve gotten this far, you probably know (a) what a database is and (b) what an API is. A question that has always bothered me is why do we need both? Allow me to further develop the question.
Imagine you’re a software engineer at Twitter (yikes). The data for tweets is stored in a database that probably looks something like this:
The code that builds the Twitter homepage needs to query this database, so you can show the latest tweets, what’s in them, who wrote them, how many likes they have, and such. A basic query to get that information might look like this:
SELECT
tweets.tweet_text,
tweets.sent_at,
authors.author_name
FROM tweets
JOIN authors ON tweets.author_id = authors.id
You’ve also got an API (well many, but this is one) that sits in front of that database. The API was built by some other software engineer, and what it does is runs the exact query above, retrieves the information from the database, and returns it to the requestor. The API request looks something like this:
GET https://api.twitter.com/tweets
This is standard practice in every engineering organization I’ve ever seen. Database. API in front of database. Query API in application, instead of querying database.
But why don’t you just write that query in your frontend code? Why do you have to go through the trouble of creating all of these different API endpoints to sit in front of your database? Why not just query it directly from your app?
There are basically two answers:
- There are a lot of good reasons to separate your database from direct queries
- There are many, many other types of APIs other than single query ones
Let us dive in.