Full Introduction of REST API
Complete Definition and Simple Example with NodeJS
What is API?
API Definition
API (Application Programming Interface) is an application that can connect several services and allows them to communicate with each other. Several types of API that are often used are REST (Representational State Transfer), SOAP (Simple Object Access Protocol), GraphQL, and gRPC (Google Remote Procedure Call).
Interface Definition
Word ‘Interface’ mean a connector or bridge between 2 objects with different characters. For example:
- GUI (Graphical User Interface) — connect User and Machine using Graphic
- CLI (Command Line Interface) — connect User and Machine using Command
- HID (Human Interface Device) — connect User and CPU using Device
Then, API (Application Programming Interface) connect Client and Server using Application/Service.
How API Works?
API bridges requests and responses between clients and servers. Requests from clients are made by the user, then validated and carried by the API. The API then conveys this request to the server in charge of processing, accessing the database, and processing it. The server will provide the results of the request processing back to the API, then it is taken and given back to the client by the API.
Back-End Development at a Glimpse
Back-end web development refers to the server side of development where you are primarily focused on how the site works. This type of web development usually consists of three parts: an application, a database and a server.
Advantages of Implementing API
- Easy Integration — APIs can help your application integrate with other applications and systems, making it easier to share data and functionality between them.
- Increased Automation — APIs can help automate tasks within your application, saving time and reducing the potential for errors.
- Better Scalability — APIs can help your application scale more easily, as they enable you to add new features and functionality without disrupting existing systems.
- Increased Revenue — By exposing your application’s functionality and data via APIs, you can create new revenue streams by allowing third-party developers to build on top of your platform.
- Improved User Experience — APIs can help create a more seamless user experience by enabling users to access your application from different devices and platforms.
- Better Security — APIs can help improve security by enabling you to control access to your application’s data and functionality, as well as monitor and audit API usage.
Easy Integration
APIs provided by delivery service providers can be used by e-commerce APIs. E-commerce does not need to access the delivery service provider’s server directly, but can make requests via API.
APIs built by e-commerce services can synchronize data presented to different clients. Multi-client integration like this becomes easier with the development of an API.
Increased Revenue
Third party API providers may charge fees to clients who use their API. The more clients who use the API they provide, the more income they earn.
Intro to REST API
REST (Representational State Transfer) is an architectural style for building web services/API that provide data through HTTP requests. It is a set of design principles for building web services that are scalable, efficient, and easy to maintain. The server exposes a set of resources and the client can interact with these resources through well-defined URLs (Uniform Resource Locators) and HTTP methods.
HTTP Request
HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web. It’s an application layer protocol that allows web browsers and servers to communicate and exchange data over the internet.
The REST API uses this protocol to communicate, including making requests. The request created has a standard structure in the form of Method, Header and Body.
HTTP Method
HTTP methods are actions that a client can request to perform on a resource identified by a URL. These methods define the type of operation that the client wants to perform on the server. Some common HTTP methods include:
- GET: Requests data from a specified resource
- POST: Sends data to be processed to a specified resource
- PUT: Full updates a specified resource with send new data that will be replace the old data
- DELETE: Deletes the specified resource
- PATCH: Applies partial modifications to a resource. It is typically used to update specific fields of an existing resource
Request Header
Contains service-related information that not related with the data requested or retrieved. This information is used by the server to send a response. For example, for request to Product resources we attach a header to send information about Content-Type, Language, Client, and Authorization token.
Request Body
The part of an HTTP request message that carries data or information sent by the client to the server. It typically contains additional parameters or payload associated with the request, such as form data, JSON or XML data, files for upload, or other content.
In requests using methods like POST, PUT, and PATCH, the request body is where the main data being sent to the server resides. However, in requests using methods like GET and DELETE, which typically don’t include a request body, the request body may be empty or not present at all.
HTTP Response
The REST API also uses this protocol to communicate, including sending response from the server back to the client. The response created has a standard structure in the form of Status Code, Header and Body.
HTTP Status Code
HTTP status codes are three-digit numbers returned by a web server in response to an HTTP request made by a client. These status codes indicate the result of the request and inform the client about the success, failure, or other conditions of the request. Here are some common HTTP status code categories:
- Informational responses (1xx) — These status codes indicate that the server has received the request and is processing it. (e.g. 100, 101, etc.)
- Successful responses (2xx) — These status codes indicate that the request was successfully received, understood, and accepted by the server. (e.g. 200: OK, 201: Create Resource, 204: No Content, etc.)
- Redirection messages (3xx) — These status codes indicate that further action needs to be taken by the client to complete the request. For example, when the requested resource has been moved to a different URL (301).
- Client error responses (4xx) — These status codes indicate that there was an error on the client’s side, such as a bad request (400), unauthorized access (401), forbidden (403), or resource not found (404).
- Server error responses (5xx): These status codes indicate that there was an error on the server’s side while processing the request. (e.g. 500: Internal Server Error, 502: Bad Gateway, 503: Service Unavailable)
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status for more status.
Header
This header contain server-related information, such as Content-Type sent back to the client, server name or version, content length.
Body
Response body is the data sent back to the client from a server to respond the request. Body contain data related to the resource. For example, resource User will send the data of the specified User (name, email, age, etc.) when client request with GET method.
Design Principles
Here are some design principles for building RESTful APIs:
- Resource Based — RESTful APIs are resource-based, which means that they expose resources (e.g., users, orders, products, etc.) as endpoints that can be accessed using HTTP methods.
- Uniform Interface — RESTful APIs should use a uniform interface, which means that the same set of HTTP methods and resource URIs should be used across the entire API. This makes it easier for clients to interact with the API and reduces complexity.
- Stateless — RESTful APIs should be stateless, which means that each request should contain all the information necessary to complete the request, without relying on any previous requests. This simplifies the API and makes it more scalable.
- Cacheable — RESTful APIs should be cacheable, which means that responses should indicate whether they can be cached or not. This can improve performance and reduce server load.
- Layered System — RESTful APIs should be layered, which means that each layer should be independent of the other layers. This makes it easier to update or replace individual layers without affecting the rest of the API.
- Client-Server — RESTful APIs should follow a client-server architecture, which means that the client should be separate from the server. This allows for greater flexibility and scalability.
Best Practices
Here are some best practices for building RESTful APIs:
- Use HTTPS for security
- Use HTTP methods correctly
- Configure appropriate header
- Use appropriate status codes
- Use pagination for large datasets
- Use versioning
- Use resource naming conventions
- Consistent response format
- Use authentication and authorization
- Provide clear documentation
- Implement HATEOAS
Resource Naming Conventions
- Use plural nouns: “/users”
- Use lowercase: “/products”✅ “/Products” ❌
- Use hyphens or underscores: “/product-categories”✅ “/product_categories”✅ “/productCategories” ❌
- Use nouns instead of verbs: “/orders”✅ “/get-orders”❌
- Use specific resource names: “/users/{userId}/orders”✅ “/users-order/{userId}”❌
- Use versioning: “{base_url}/v1/auth/login”✅ “{base_url}/auth/login”❌
- Use query parameter: “/products?search=backpack”✅ “/products?page=2”✅ “/products?sort=name&type=asc”✅
Consistent Response Format in an API
Always use JSON for every response. A text-based file format that is generally used in the process of exchanging data between servers and clients. JSON files have the .json extension and use a data format that is easy for humans to understand, lightweight, and structured based on object syntax in JavaScript. Besides JSON, you can also use XML format.
Use Authentication and Authorization
Authentication is the process of verifying the identity of a user or entity. It involves validating the credentials provided by the user, such as a username and password, or a security token. Common authentication in RESTful APIs include basic authentication, token-based authentication, OAuth, and JSON Web Token (JWT).
Authorization is the process of granting or denying access to a resource based on the authenticated user’s identity, privileges, and permissions. It involves defining rules and policies that determine what actions a user is allowed to perform on a resource.
Use HATEOAS
HATEOAS (Hypermedia as the Engine of Application State) is a constraint in the REST architectural style that suggests including hypermedia links in the response of an API to dynamically guide clients through the available interactions with the API.
In simpler terms, HATEOAS allows a client to interact with a RESTful API entirely through hypermedia links provided in the responses. This means that the API response not only includes the requested data but also includes links to related resources and actions that the client can take next.
HATEOAS is considered a constraint of Level 3 in the Richardson Maturity Model, which states that Level 3 APIs are fully RESTful and include hypermedia controls in their responses. However, it’s important to note that the Richardson Maturity Model is just one framework for evaluating RESTful APIs and may not be universally applicable to all API designs or contexts.
Build Very Simple RESTful API With NodeJS
Requirements
- NodeJS
- NPM
- Code Editor
- MySQL Database
- Postman
NodeJS
NodeJS is a runtime environment for JavaScript that is open-source and cross-platform. By using NodeJS, JavaScript can be run anywhere, not only limited to the browser environment. In implementing the API, NodeJS runs in a browser using an engine called V8 from Chrome.
NPM & Package
NPM (Node Package Manager) is a package manager that allows JavaScript developers to find and install packages or libraries to use in their applications. A package or library is a collection of JavaScript module files that function to add various features to an application or script. Without this, the software developer or engineer would have to write new code for every required function.
ExpressJS
ExpressJS is a Backend Web Application Framework for building RESTful APIs using NodeJS. Express is open source and free under the MIT license. Express is a standard NodeJS server framework for creating APIs.
API Building Step by Step
1. Open your IDE
2. Code!
— Create project
npm init -y
— Install dependencies
npm install express mysql dotenv
npm install nodemon -g
npm install morgan -d
— Setup db and .env
— — Start MySQL service
— — Import or create database
https://github.com/sekarmk03/simple-rest-api/blob/master/api_demo.sql.zip
— — Create .env file
https://github.com/sekarmk03/simple-rest-api/blob/master/.env
— — Create db folder in the project
— — Create db.conn.js file
— — Add database configuration to db.conn.js file
https://github.com/sekarmk03/simple-rest-api/blob/master/db/db.conn.js
— — Create function executeQuery (add function to db.conn.js)
— Create app.js
https://github.com/sekarmk03/simple-rest-api/blob/master/app.js
— Create controllers
https://github.com/sekarmk03/simple-rest-api/blob/master/controllers/student.js
— Create routes
https://github.com/sekarmk03/simple-rest-api/blob/master/routes/student.js
— Full Code
https://github.com/sekarmk03/simple-rest-api
3. Test your API
Test your API in Postman! See this API documentation: https://documenter.getpostman.com/view/15801526/2s93m4Z3pR