Introduction to GraphQL
In this lesson, we'll cover the basics of GraphQL; what it is and how to use it. We'll also understand how it fits the course's subject.
In the course introduction, we mentioned that we're going to use a Postgres database to store our comments. In our application, we need to be able to do two things:
Add new comments — insert new entries to the database.
Display the comments in the UI — extract them from the database.
But how exactly do we communicate with the database from a frontend application?
That's where Hasura comes into play! It will generate GraphQL APIs from a database. That way, from the frontend (client), we will communicate with Hasura through GraphQL, and beneath, Hasura will handle accessing the database.
And since we're going to use GraphQL, let's first talk about it a bit.
What is GraphQL?#
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
When we're working on an application that requires resources stored in a database, we don't directly access the database from the frontend code — we have a server for it.
Why we don't access a database directly from a frontend application?
If we were to connect a frontend application to a database, we would need to put the database credential in the frontend code. However, the frontend code is accessible to everyone, which would cause the credentials to leak. Users can't access the server code, so we put the database connection code there.
The client sends requests to the server to fetch or modify data. The server handles these requests — accessing the database and possibly performing some additional logic. Then it returns a result to a client. It can be, for example, a list of items that the client application wanted to fetch or a message that the request was successful (for example, after creating a new item). If something goes wrong, the server will return an error message. A common way to handle client-server communication (and you might be familiar with it) is using REST APIs. Let's quickly take a look at it!
A quick recap of REST APIs#
With REST APIs, the client sends a request to a particular endpoint to access a particular resource. It needs to be sent using an HTTP method expected by the server — GET, POST, PUT, PATCH, or DELETE. The request body and the response format are usually agreed upon between the frontend and backend teams. The backend team implements and exposes APIs that frontend applications can use. A sample list of endpoints can look like this: