REST vs GraphQL.png
Cover image for joseph_appsmith

Joseph Petty Verified userVerified user

Sr. Developer Advocate

Appsmith

An Intro to REST and Graphql Apis

An API, or Application Programming Interface, is a defined standard, allowing two or more computer systems to interact and exchange data. When it comes to APIs for transmitting data across the web, there are two main standards used today: REST and GraphQL. If you're new to REST and GraphQL APIs, this guide will give you a quick overview to help you get started using APIs in Appsmith. 

HTTP Requests

APIs that communicate over the web do so by making HTTP requests. Both REST and GraphQL use HTTP requests as the channel of communication, usually over port 80 (http) or 443 (https).

HTTP Methods 

HTTP methods, also known as HTTP verbs, represent the actions that can be performed on various resources. They dictate the nature of the operation to be carried out on the resource. Below are the commonly used HTTP methods:

Method Description
GET Retrieves data or a resource from the server based on the given URI.
POST Submits data to the server to create a new resource or trigger a specific action.
PUT Updates or replaces the resource identified by the URI with the provided data.
DELETE Removes or deletes the resource identified by the URI.
PATCH Applies partial modifications to a resource, altering only specific parts identified in the request.
HEAD Retrieves only the header information for the resource, excluding the actual content.
OPTIONS Requests information about the communication options available for the resource or server.

Each request consists of the request method, and an endpoint URL, targeting a specific URI (Uniform Resource Identifier), and may also contain headers, url parameters, and a body.  

Headers contain metadata about the request, including content-type or authorization details. Parameters or query strings in the URI are used to specify record IDs, search terms, and other options for working with the endpoint. 

The request Body transmits additional data, which is usually JSON, but also supports many other formats. 

Body Type Description Example
JSON A lightweight data interchange format that's easy for humans to read and write, and easy for machines to parse and generate.     { "name": "John Doe", "email": "john@example.com" }
XML A markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.  <user><name>John Doe</name><email>john@example.com</email></user>
Form URL Encoded A way to encode key-value pairs in a body similar to query parameters, used primarily for form submissions.     name=John+Doe&email=john%40example.com
Multipart Form Data A way to send data that may include files, allowing each part of the message to have its own content type and disposition.  --boundary\r\nContent-Disposition: form-data; name="name"\r\n\r\nJohn Doe\r\n--boundary\r\nContent-Disposition: form-data; name="file"; filename="file.txt"\r\nContent-Type: text/plain\r\n\r\n(file content here)\r\n--boundary--
Plain Text Simple text without any specific format, often used for plain-text email or log entries. This is a plain text message.
Binary Raw binary data, typically used for file uploads, such as images or documents. (Binary data represented in bytes, e.g., a .png or .pdf file)

Together, the method, endpoint, parameters, and body make up an HTTP request, which coordinates the transmission of information between clients and servers in a standardized manner.

REST: Representational State Transfer

The REST API standard has been around since 2000, and it is still the most common type of API used today. REST defines a set of constraints for how the architecture of a system should behave, so that any system following the standard should be compatible with any REST API client (website, end user application or tool like Postman).

Characteristics of REST APIs

  • Stateless Nature: Each request contains all necessary information, aiding scalability and performance by eliminating the need for session data storage.
  • Resource-Based Interaction: Resources are identified by unique URIs, accessible through standard HTTP methods like GET, POST, PUT, and DELETE.
  • Uniform Interface: Standardized set of methods and response formats simplify API development and consumption.
  • Cacheability: Responses can be cached, enhancing performance and reducing network traffic.
  • Layered System: Allows integration of intermediaries like proxies without impacting the overall system, adding to flexibility and scalability.
  •  

REST APIs are easier to learn than GraphQL, but it can be more difficult to fetch resources from multiple endpoints and join data together. That's where GraphQL comes in. 

GraphQL: Efficient and Flexible Data Fetching

GraphQL, developed by Facebook and released in 2015, emerged to streamline complex data fetching and mitigate over-fetching issues associated with traditional REST APIs. With GraphQL, the HTTP verb is always a POST, because the request itself is in the body, instead of using URL parameters. 

Characteristics of GraphQL

  • Strongly Typed: Enforces specific data types for each field, aiding validation and handling.
  • Query Language: Allows clients to request precisely the required data, reducing data redundancy and enhancing performance.
  • Single Endpoint: Simplifies data fetching by consolidating requests through a single endpoint.
  • Declarative: Clients specify what data they need, simplifying data fetching strategies.
  • Schema-Driven: Defines a clear structure and available queries/mutations for easier development.

Authentication Methods

Most APIs will require some type of authentication, usually a token or API key provided in the header. This lets the server know who's making the request, so it can decide which resources can be accessed. 

Below is an overview of the most common authentication methods used in APIs and web applications.

Method Description Use Cases Advantages Disadvantages
API Key A simple token generated by the server, provided to the client to include in their requests for identification. Internal services, low-security applications Easy to implement and use. Limited security; can be easily shared or exposed if not handled securely.
Basic Authentication Uses a username and password encoded in base64 and included in the HTTP header for each request. Simple applications, legacy systems Simple to implement and understand. Credentials are exposed if not sent over HTTPS; not suitable for high-security applications.
OAuth 2.0 A widely used authorization framework that allows third-party applications to access user data without exposing passwords. Third-party integrations, user consent flows Provides a secure way to grant limited access; supports scopes and granular permissions. Complex to implement; involves redirects and multiple steps for token exchange.
OpenID Connect An identity layer on top of OAuth 2.0 that provides authentication and identity information in a standardized way. Single sign-on (SSO), user identity management Extends OAuth 2.0 with identity verification; supports federated identity management. Requires a deeper understanding of OAuth 2.0; may be overkill for simple applications.
JWT (JSON Web Token) A compact, URL-safe token that contains claims about a user and is digitally signed, allowing verification of the token's authenticity and integrity. Stateless authentication, mobile applications Self-contained token with claims; reduces server load by avoiding session storage. Tokens can become large if many claims are included; requires secure token storage on client side.
SAML (Security Assertion Markup Language) An XML-based protocol used for exchanging authentication and authorization data between parties, typically used in enterprise SSO scenarios. Enterprise applications, SSO systems Mature standard; widely supported in enterprise environments; supports complex use cases. Verbose XML format; complex to set up and manage; mainly used in enterprise settings.

HTTP Error Codes

When working with REST or GraphQL APIs, you may receive different error codes from the server due to missing or incorrect data in your request. The error will have a number representing a certain category of error, and may contain additional debugging info, like the name of a required property that is missing in the request. 

Below is a table that outlines the most common HTTP error codes, their meanings, and typical scenarios in which they occur.

Status Code Name Description Typical Scenarios
400 Bad Request The server cannot process the request due to client-side input errors. Malformed request syntax, invalid request message framing, or deceptive request routing.
401 Unauthorized Authentication is required, or provided credentials are invalid. Accessing protected resources without valid credentials.
403 Forbidden The server understands the request but refuses to authorize it. User is authenticated but does not have permission to access the resource.
404 Not Found The requested resource could not be found on the server. Typo in URL, deleted resource, or incorrect routing configuration.
405 Method Not Allowed The request method is not supported for the requested resource. Using POST on a read-only resource that only supports GET.
408 Request Timeout The server timed out waiting for the request from the client. Slow or interrupted network connection between client and server.
409 Conflict The request could not be processed due to a conflict with the current state of the resource. Simultaneous updates to a resource causing a versioning conflict.
500 Internal Server Error The server encountered an unexpected condition that prevented it from fulfilling the request. Server misconfiguration, unhandled exceptions in server-side code.
502 Bad Gateway The server, while acting as a gateway or proxy, received an invalid response from the upstream server. Issues with upstream servers or third-party services.
503 Service Unavailable The server is currently unable to handle the request due to temporary overload or maintenance. Server is down for maintenance or experiencing heavy load.
504 Gateway Timeout The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server. Network issues or performance problems with upstream servers.

Integrating with a new API

When integrating with a new API, the first thing you should do is check out its documentation and determine the type of API (REST or GraphQL) and the authentication method used. You'll most likely have to create an account and API key, and possibly add scopes to enable access to the specific resources needed for your use case. 

Once you have your API key, create an Authenticated API Datasource in Appsmith to securely store the key on the Appsmith server, instead of including the key in your app definition. From there, you can begin adding new APIs under the datasource, and follow the API's documentation to determine the correct endpoints and other details needed in your request. 

Conclusion

Together, REST and GraphQL APIs make up the vast majority of all APIs used on the web today. This guide has covered the basics of both standards and should give you a solid foundation to begin integrating your first API with Appsmith. For detailed instructions on a specific API, check out our topics by integration page.