Core concept of API and CGI

Tirth Patel
3 min readAug 28, 2020

Have you ever thought of how can we run a program in another OS without login or any networking. Here the concept of API comes in play. API is Application Programming Interface. The core concept working behind the scene is CGI.

CGI is Common Gateway Interface. CGI is like a gate which allows any user to go in the OS and run the program. Every web-service or web programs work on the concept of CGI. Whenever we want to run a program in another OS without networking or login access, make the code as CGI code in the web server. API also works on the concept of CGI

In RedHat, the httpd itself configures and give access to use CGI. Any code written in the folder /var/www/cgi-bin is treated as CGI. Here the client can only run the program but cannot change the code. While in /var/www/html the file is treated as web page and httpd provides the facility of viewing the page only.

moving to /var/www/cgi-bin

There are several things that should be taken care of when creating a CGI program.

  1. Make the code executable.

In RedHat, we can make any file executable by chmod +x file_name command.

Making file executable

After making executable we can run file by command ./filename

2. Add the language interpreter by hashbang symbol : (#!)

Provide the exact path where the language is located in OS. Here i am using python as interpreter as the code written is in python.

3. Provide the content type to the program as it is finally going to be a type of web page. Here we need to provide the statement print(“content-type: text/html”) at the starting of the program. It should be followed by the print() so that the interpreter can understand the difference between the header and the content.

Accessing the cgi through ip address

So now cgi code can be run and tested on the browser. To access the cgi code the client need to provide the URL on web browser. URL should be in the following format

http://ipaddress/cgi-bin/filename

Running on another system

Note : If getting error try stopping firewall. Here in RedHat the command, systemctl stop firewalld will stop the firewall.

So every CGI program is nothing but API’s that can be accessed by any user. This is how API works.

--

--