Skip to Content

What is REST API and why it is used?

REST (Representational State Transfer) API is a software architecture style for building scalable web APIs. REST APIs allow communication between a client and a server through a set of standard operations like GET, POST, PUT, DELETE. REST uses HTTP protocol for communication which makes it fast and independent of platforms.

What is an API?

API stands for Application Programming Interface. It acts as an interface between two applications and enables them to talk to each other. APIs allow different software applications to communicate and exchange data directly without any user intervention.

For example, the weather bureau has weather data like temperature, humidity, wind speed etc. A weather app can use the weather API provided by the weather bureau to show the latest weather data inside the app. So the API serves as the interface between the weather app (client) and the weather bureau (server).

What is REST?

REST stands for REpresentational State Transfer. It is a software architectural style for developing web services.

REST guidelines recommend using explicit HTTP operations (GET, POST, PUT, DELETE) to manipulate data over HTTP protocol. This makes REST web services completely stateless. All the required data is contained in each request so the communication is self-contained.

The key principles of REST APIs are:

  • Client–server – Client and server must be separate applications.
  • Stateless – No client information is stored between requests.
  • Cacheable – API responses must define themselves as cacheable or not.
  • Uniform interface – Resources are identified in requests.
  • Layered system – Client cannot tell if it’s connected directly to server.
  • Code on demand (optional) – Servers can extend client functionality by sending code.

REST API Characteristics

Below are some key characteristics of REST APIs:

  • Client-Server: REST application has a client-server architecture. Client sends requests, server provides resources.
  • Stateless: No client information is stored between requests. Each request has all the required information.
  • Cacheable: API responses define if they can be cached or not.
  • Layered System: Client cannot determine if it is connected directly to server or going through proxies, load balancers etc.
  • Uniform Interface: Resources are manipulated using standard HTTP methods like GET, POST, PUT, DELETE.
  • Resource identification in requests: Requests contain all the information required to identify resource.

Why use REST APIs?

Below are some of the key advantages of using REST APIs:

  • Lightweight: REST uses less bandwidth and resource than heavy protocols like SOAP.
  • Platform independent: REST can be used across languages and platforms like Java, Python, .Net etc.
  • Scalability: REST is built on top of HTTP. Since HTTP is scalable, REST can handle more transactions as traffic increases.
  • Separation of concerns: Client and server can evolve independently which promotes software portability.
  • Visibility and reliability: REST uses standard HTTP methods and error codes which make APIs visible and reliable.
  • Speed: REST requires less bandwidth thus improves response times.
  • Caching: REST responses can be cached to further improve performance.

Common operations in REST API

REST APIs use HTTP methods to manipulate resources on server. Below are the main HTTP methods used:

GET

The GET method requests data from a server. It only retrieves data and does not modify anything on server.

POST

POST method requests server to create a resource. It is often used to submit data to be processed like user details, file upload etc.

PUT

PUT method replaces existing resource with new data. It is used to update an entire resource.

PATCH

PATCH method updates a part of an existing resource, not the whole. It is used for partial updates.

DELETE

DELETE method deletes an existing resource.

REST API Best Practices

Below are some best practices for designing REST APIs:

  • Use HTTP methods properly – Use GET for retrieving, POST for creating, PUT/PATCH for updating, DELETE for deleting resources.
  • Use plural nouns for naming resources – Use plural nouns like users, products, books etc. Avoid singular.
  • Use sub-resources for relations – If a resource is related to another resource use subresources. For example, /authors/1/books for all books by author 1.
  • Handle errors gracefully – Return proper error response and status codes like 400 (Bad Request) or 500 (Internal Server Error).
  • Support filtering, sorting and pagination – Allow querying resources by field values, ordering results and specifying result size.
  • Make resources self-descriptive – Resources returned in response should contain enough information to identify them. For example, user resource should return id, name, email etc.
  • Use HTTP status codes to indicate status – Use status codes like 200 (Success), 201 (Created), 404 (Not Found) etc. to provide extra meaning.
  • Provide API documentation – Create detailed documentation of resources, operations, sample requests/responses, errors etc.
  • Version your API – When making breaking changes, version your API and support older versions for some time.

Common status codes used in REST API

REST APIs use HTTP status codes to provide API responses with meaningful status information. Below are some commonly used HTTP status codes:

Status Code Meaning
200 OK – Request was successful
201 Created – Resource was created
400 Bad Request – Invalid request
401 Unauthorized – Authentication required
403 Forbidden – Server refuses to respond
404 Not Found – Resource does not exist
500 Internal Server Error – Server encounter unexpected error

REST API security best practices

Some security best practices for REST APIs include:

  • Use HTTPS – Always use HTTPS to secure communication over SSL/TLS.
  • OAuth 2.0 – Use OAuth 2.0 framework for authentication and authorization.
  • Rate limiting – Limit number of requests clients can make per hour to prevent abuse.
  • Input validation – Validate all inputs on server to prevent common attacks like SQL injection, cross-site scripting etc.
  • Token based authentication – Use JWT tokens to authenticate users and protect API access.
  • Encrypt sensitive data – Encrypt any sensitive data like passwords in database.
  • Host only over private networks – Do not expose APIs directly to public internet. Use private VPCs.
  • Regularly patch and update – Keep API implementation, dependencies, TLS etc. up-to-date.
  • Use role based access – Restrict API access to only required roles.
  • Audit APIs regularly – Monitor API activity for suspicious requests.

REST API vs SOAP API

Below is a comparison between REST and SOAP APIs:

REST SOAP
Uses lighter weight protocols like HTTP, JSON Uses XML for messaging
Better performance as overhead is low Slower compared to REST due to XML messaging overhead
Supports different data formats like JSON, XML, YAML etc. Supports XML only
Architecture focuses on resources Architecture focuses on operations
Stateless, makes caching easier Supports stateful operations
Easier to implement, less development overhead Requires more bandwidth and resource

Examples of popular REST APIs

Below are some examples of popular REST APIs used by developers:

  • Twitter API – Provides REST APIs to read and write Twitter data. Useful for integrating tweets into apps.
  • Stripe API – Provides APIs for payment, invoicing, fraud prevention etc. Used to accept payments online.
  • Twilio API – Provides SMS, Voice and other communication APIs. Used for notifications and 2FA.
  • GitHub API – Provides REST APIs to interact with GitHub repositories, users etc programatically.
  • Google Maps API – Provides REST APIs for maps, routes, geocoding, places etc.
  • YouTube API – Provides REST APIs to integrate YouTube videos and manage playlists, channels etc.

Conclusion

REST API is a lightweight, scalable architecture used for exchanging data over web using HTTP protocol. It offers faster performance and flexibility compared to other architectures like SOAP. REST uses standardized and explicit HTTP methods like GET, POST, PUT, DELETE to manipulate resources.

REST APIs follow best practices like proper use of HTTP methods, meaningful status codes, self-descriptive error handling etc. This results in APIs that are easy to use, develop and integrate with. REST has become ubiquitous for building scalable public APIs because of these advantages.