ORM vs Web API – Key Differences

apientity-frameworkorm

I'm struggling to understand the differences between an API such as a REST API and an ORM such as Entity Framework. I would also like to understand the benefits of each and in what situations either should be used.

It seems to me that they both act as a middle man and enable you to access and manipulate data from a database within a programming language.

Thanks

Best Answer

Calling something an API doesn't tell you much about it. It's a very broad category, so very unrelated things will fall into it. But lets take a look at the two you mentioned.

Representational State Transfer (REST) is an architectural style that defines a set of constraints and properties based on HTTP.

https://en.wikipedia.org/wiki/Representational_state_transfer

This has become a very common method for websites to request data from a server. That being said, it is just one way for two remote systems to talk with each other. It doesn't have to use a database at all.

For example, you might send a GET request to somedomain.com/increment/35 and get 36 returned as a response. No database needed. Just some code adding 1 to whatever you provide it.

ORM in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.

https://en.wikipedia.org/wiki/Object-relational_mapping

I feel like that quote leaves out the common and perhaps only decent use-case, which is to serve as a middleman between your code and a database. The idea is that it will simplify the access and modification of database entries.

For example, instead of writing out SQL statements in your code SELECT something FROM myTable, you could write something like

entries = orm.myTable.getAll() // This replaced the SELECT call
loop entries as entry
  print(entry.something)
end loop

One benefit to this is that if that table's name changes, you only need to update the ORM rather than all the SELECT calls. One downside is the complexity that the ORM brings with it. If it saves time, use it. If not, don't.

You may find yourself using both a REST API and an ORM in your projects, or perhaps only one or the other. I'd suggest using some tools that implement each pattern useful in gaining a better understanding of them. At the very least read their documentation. It'll help you understand their purpose much faster. Every language has them, but here are a couple in Javascript: