Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an api compare to directly querying your database

Tags:

I am kind of confused about when an API is needed. I have recently created a mobile app with flutter and cloud firestore as the database where i simply queried and wrote to the database when needed. Now i am learning full stack web development and I recently watched a tutorial where he built like an Express API with GET, POST, and DELETE functionality for a simple item in the database.

Coming from a background where i just directly accessed the database i am not sure why an API in this case is necessary, is it so I wouldnt have to rewrite the queries every time? This is a very simple project so he's definitely not making a 3rd party api for other developers to use. Am i misunderstanding what an API does exactly?

It was really simple, there was one collection in a MongoDB database and he was using postman to read and write to and from the database to check if it works.

like image 720
Potato Avatar asked Nov 13 '19 09:11

Potato


2 Answers

API is a standard way with which your front-end (web/mobile) stores/gets information for your application. Your front-end can/should not directly access database ever. Understand the purpose of front-end which is to just display the interface and should do minimal processing. All the application logic should be at your backend (API server) which is exposed to your frontend via API (GET, POST etc) calls. So to store an item in your database, you will write data storing logic in your backend, and expose an API end-point which when triggered will perform the storing operation. That API call should be used by your front-end to trigger the storing process. In this way your logic of storing/database or any other thing is not exposed, only the API URL is. The purpose of front-end is to be exposed whereas backend/database should never be exposed and used from front-end

like image 155
Muhammad Ahsan Avatar answered Jan 04 '23 17:01

Muhammad Ahsan


May be for you, an API is not necessary. But, the use-cases of an API is a lot.

For example:

  • You don't have to write business logic for every platform. (iOS, Android, Web, Whatever)
  • Your app will be lightweight since some computation would be offloaded to server.
  • Your app can be reverse engineered to get secret informations. (or, Your secret algorithm may be?)
  • What if you need to store something in filesystem that you want share with others?

Also a good read: Why we should use REST?

like image 23
Shihab Avatar answered Jan 04 '23 17:01

Shihab