Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Understanding the Basics of HTTP

Jul 10, 2019 • 14 Minute Read

Introduction

We are living in a world where we are surrounded by information, and the internet is the main interface between us and that information. We use websites, web apps, mobile apps, etc. and, within seconds, we can obtain information very easily. Simply, we are using Google typing "https://www.google.com" and with a single click we get Google page. Have you ever thought about how it works? Do you want to know? If you’re here, I can only assume the answer is, “Yes,” and we are going to describe it.

HTTP stands for Hypertext Transfer Protocol

Web applications are work by exchanging information. ”Exchanging information, how is it possible?” Whenever you surf the web, your browser sends an HTTP request messages for HTML pages, images, scripts, and style sheets. Web servers handle these requests by returning response messages that contain the requested resource. HTTP is the Bridge for Communication; it enables the exchange of information over the internet. HTTP is the bridge, but for communication, we the WWW (World Wide Web) which is responsible for the connection between client and server.

In this guide, we will learn about HTTP and how to exchange information or data between the client and server.

How Does HTTP Works

All the communication between the client and server happens via request and response. HTTP has HTTP Requests and HTTP Responses to communicate with.

This is what happens under the hood:

  • The browser (client) sends an HTTP request to the web.
  • The web server receives the request.
  • The server runs an application to process the request.
  • The server returns an HTTP response (as an output) to the browser.
  • The browser receives the response.
  • You can see the data that you want in the browser.

Getting Started

Before getting started with the guide, I will let you know we are using Angular7 to handle HTTP. So, make sure you have Node.js in your system; if not, install it from here.

The next thing you need to do is install Angular; let's install it by npm.

      npm install -g @angular/cli
    

Note: It is recommended to have an IDE; some of the best choices are Visual Studio Code or JetBrains WebStorm.

Angular is a JavaScript framework which allows you to be able to create reactive, single-page applications. This is a leading front-end development framework which is regularly updated by Angular. Angular 7 is entirely based on components. It is beneficial to understand HTTP, so we are using an Angular application to understand HTTP.

Jumping to the Code

I am assuming that you now have Angular 7 setup, so let's jump into a simple example code.

Step 1: Start a New Project

Since Angular is a framework, we need to follow some standards of the framework. To create a new project in Angular, use the command ng new project_name. I have named my project HTTP tutorial.

      ng new HTTP tutorial
    

This will create a tutorial directory with the following contents:

      HTTP tutorial
├── node_module               -- Installed Angular packages available in the project
└── src                       -- Contains the main code files.
    ├── app folder            -- Contains the files for app components
    ├── app.component.css     -- Cascading style sheets code for app component.
    ├── app.component.html    -- The HTML file related to the app component
    ├── app.component.spec.ts -- Unit testing file related to app component.
    ├── app.component.ts      -- Write view logic behind the component.
    └── app.module.ts         -- Includes all the dependencies for the website.
├── package.json              -- npm configuration file include packages version
├── package-lock.json         -- Auto-generated and modified file.
├── angular.json              -- Configuration file related to your angular application
├── .gitignore                -- File is related to the source control git.
├── .editorconfig             -- Maintain consistency in code editors to organize.
├── assets folder             -- Placeholder for resource files.
├── environments folder       -- Hold the environment configuration constants
├── browserlist               -- Adjusts the CSS to support a list of defined browsers.
├── favicon.ico               -- Small icon that appears next to the browser tab
├── index.html                -- Entry file holds the high-level container application.
├── karma.config.js           -- Config file for the Karma Test Runner
├── main.ts                   -- The main ts file that will first run.
├── polyfills.ts              -- Used to cover whatever feature missing from browser.
├── styles.css                -- Global CSS file which is used by an application.
├── tests.ts                  -- Use to traverse all the unit tests in the application
├── tsconfig.json             -- Typescript compiler configuration file.
├── tsconfig.app.json         -- Override the tsconfig.json file with app configurations.
├── tsconfig.spec.json        -- Override the tsconfig.json file with app unit test configurations.
    

Step 2: Creating Our First Angular Application for Handle HTTP

Setting up the HttpClient: This is the first step to import HttpClientModule in src/app/app.module.ts.

      import { HttpClientModule } from '@angular/common/http';
@NgModule({
    declarations: [
        AppComponent
    ],
imports: [BrowserModule,HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule { }
    

Create one class model: Use the command ng generate class class_name. I have named class name as employee.

      ng generate class employee
    

After a class is generated, you have to add objects:

      export class Employee {
    id: number;
    employee_name: string;
    employee_salary:number;
    employee_age:number;
}
    

For HTTP URL calls, we need a service file in Angular. Use the command ng generate service service_name. I have named class name as apicall.

      ng generate service apicall
    

Why services?

Components shouldn't fetch or save data directly, and they certainly shouldn't knowingly present fake data. They should focus on presenting data and delegate data access to a service. Here we are using apicall.service.ts.

After you’ve generated apicall.service.ts, import the HTTP client and initialize it in the constructor as given below.

      import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from './employee';
    

In the constructor:

      constructor(private httpClient: HttpClient) {}
    

To run in Angular, you can use the following command:

      ng serve
    

If you want to run in an open browser directly, use below command:

      ng serve --open
    

Step 3: Our First HTTP Request

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource.

Lets see all the methods for making requests and its implementations one by one.

GET Method: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

Follow the below code for getting all records of the Employee.

In apicall.service.ts:

      public nextPage: string = "";
public getEmployes(url?: string){
    return this.httpClient.get<Employee[]>(`http://dummy.restapiexample.com/api/v1/employees`);
}
    

In app.component.ts:

      getEmployeeList(){
    this.apiService.getEmployes().subscribe((res)=>{ this.apiService.getEmployes(this.apiService.nextPage).subscribe((data:Employee[]) => {
        console.log(data);
        });
    });
}
    

In app.component.html:

      <table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Salary</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let emp of employees">
            <td>{{emp.employee_name}}</td>
            <td>{{emp.employee_salary}}</td>
            <td>{{emp.employee_age}}</td>
            <td >
                <button (click)="deleteEmployeeData(emp.id)">Delete</button>
            </td>
        </tr>
    </tbody>
</table>
    

From the above code, your request and response are given below:

Requested URL:

Url: https://dummy.restapiexample.com/api/v1/employees

Server Response:

      {
    "id":"81164"
    

GET Record by ID:

Follow the below code for getting a single record of the Employee.

In apicall.service.ts:

      public getEmployeeById(id: number){
    return this.httpClient.get(`http://dummy.restapiexample.com/api/v1/employee/${id}`);
}
    

In app.component.ts:

      getEmployee(id:number){
    this.apiService.getEmployeeById(id).subscribe((res:Employee[])=>{
      console.log(res);
    });
}
    

From the above code, your request and response are given below:

Requested URL:

Url: https://dummy.restapiexample.com/api/v1/employee/81164

Server Response:

      {
    "id":"81164",
    "employee_name":"XT4KT3OOPY",
    "employee_salary":"14137",
    "employee_age":"12",
    "profile_image":""
}
    

POST Method: The POST method is used to submit an entity to the specified resource, often causing a change in the state or side-effects on the server.

Follow the below code for creating a new Employee.

In apicall.service.ts:

      public createEmployee(employee: any){
    return this.httpClient.post(`http://dummy.restapiexample.com/api/v1/create`,employee);
}
    

In app.component.ts:

      createEmployeeData(){
    this.apiService.createEmployee(this.empPost).subscribe((res)=>{
        console.log("Created a employee");
    });
}
    

In app.component.html:

      <form>
<input placeholder="Enter Employee Name" [(ngModel)]="empPost.name"/>
<br/>
<input placeholder="Enter Employee Salary"[(ngModel)]="empPost.salary">
<br/>
<input placeholder="Enter Employee Age" [(ngModel)]="empPost.age"/>
<br/>
<button type="submit" (click)="createEmployeeData()">Save</button>
</form>
    

From the above code, your request and response are given below:

Requested URL And Data:

      Url: http://dummy.restapiexample.com/api/v1/create
Data: {"name":"abcd","salary":"123","age":"23"}
    

Server Response:

      {
    "name":"abcd",
    "salary":"123",
    "age":"23",
    "id":"91614"
}
    

PUT Method: The PUT method replaces all current representations of the target resource with the request payload.

Follow the below code for updating an Employee record.

In apicall.service.ts:

      public updateEmployee(employee: any){
    return this.httpClient.put(`http://dummy.restapiexample.com/api/v1/update/${employee.id}`,employee);
}
    

In app.component.ts:

      updateEmployeeData(){
    this.apiService.updateEmployee(this.empPost).subscribe((res)=>{
        console.log("Updated the employee");
    });
}
    

In app.component.html:

      <form>
<input placeholder="Enter Employee Name" [(ngModel)]="empPost.name"/>
<br/>
<input placeholder="Enter Employee Salary"[(ngModel)]="empPost.salary">
<br/>
<input placeholder="Enter Employee Age" [(ngModel)]="empPost.age"/>
<br/>
<button type="submit" (click)="updateEmployeeData()">Update</button>
</form>
    

From the above code, your request and response are given below:

Requested URL And Data:

      Url: http://dummy.restapiexample.com/api/v1/update/91614
Data: {"name":"abcde","salary":"20000","age":"23"}
    

Server Response:

      {
    "name":"abcde",
    "salary":"20000",
    "age":"23",
    "id":"91614"
}
    

DELETE Method: To Delete data from the server, we are using the Delete method.

Follow the below code for deleting the Employee record.

In apicall.service.ts:

      public deleteEmployee(id: number){
    return this.httpClient.delete(`http://dummy.restapiexample.com/api/v1/delete/${id}`);
}
    

In app.component.ts:

      deleteEmployeeData(id:number){
    this.apiService.deleteEmployee(id).subscribe((res)=>{
        console.log("Deleted a employee");
    });
}
    

From the above code, your request and response are given below:

Requested URL:

Url: https://dummy.restapiexample.com/api/v1/delete/91626

Server Response:

      {"success":{"text":"successfully! deleted Records"}}
    

Conclusion

So, you have successfully built an Angular application where we give complete details about HTTP and how it works on our request to get a response from the server.

Here are some of the ways that you can expand your code for learning purposes, if you are curious:

  • Get all the records of the employees.
  • Get a single record using the id of the employee.
  • Created the new records.
  • Updated the records of the employee.
  • Delete the employee records.

Now you should understand how HTTP is used for communication. Mobile apps are very famous these days and keeping all data on phone does not makes sense as it changes every second; and hence these apps uses HTTP for fetching and sending data over the Internet.

For checking how requests and responses act on any HTTP URL you are working with, you can use Postman.