Hypertext Application Language (HAL) is a standard that is used to establish conventions for expressing hypermedia controls, such as links, with JSON. It is considered as a generic media type through which web API can be developed and exposed as a series of links.
In this article, we will be using the Flask-HAL module that can be used to integrate HAL specifications with the flask. the main features of this module are –
- Easy integration to the structured format of HAL.
- Provides most of the functionalities of HAL provided including embedded docs, links, and documents.
Installation
To install this module type the below command in the terminal.
pip install Flask-HAL
Functions Used
- Document(data, links, embedded): This is a collection of embedded documents, links, and data associated.
- Embedded(data, link, embedded): Providing information regarding nested resources and their links.
- Link(resource, hyperlink): Includes resource with its associated hyperlinks and metadata. Link class is of type Collection().
Example 1: Links and Documents
After installing the library, HAL, link, and document classes need to be imported. The document is initialized with data, along with its links, which comprise of resources and its hyperlink. Self-link is included as part of the HAL document.
Python3
from flask import Flask from flask_hal import HAL, document, link # initializing HAL with app context app = Flask(__name__) HAL(app) # Links with data in document. @app .route( '/doc' ) def doc(): return document.Document(data = { 'message' : 'Representing Links and Documents for Flask HAL GFG' }, links = link.Collection( )) if __name__ = = "__main__" : app.run(debug = True ) |
Output: Go to the URL http://127.0.0.1:5000/doc
Example 2: Working with Embedded
Embedded docs are of a similar class as Document, just another key is used to define the key value for the embedded doc. Embedded class needs to be imported.
Python3
from flask import Flask from flask_hal import HAL, document, link from flask_hal.document import Embedded # initializing HAL with app context app = Flask(__name__) HAL(app) # Links with data in document. # including embedded. @app .route( '/doc' ) def doc(): return document.Document(data = { 'message' : 'Representing Links and Documents for Flask HAL GFG' }, links = link.Collection( ), embedded = { 'nesting' : Embedded( embedded = { 'double_nesting' : Embedded( data = { 'study' : "Its Embedded!" }, links = link.Collection( link.Link( link.Link( 'practice-embed' , ) )})}) if __name__ = = "__main__" : app.run(debug = True ) |
Output: