0% found this document useful (0 votes)
20 views7 pages

Understanding HTTP Methods and REST APIs

Uploaded by

vaidehithaware
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views7 pages

Understanding HTTP Methods and REST APIs

Uploaded by

vaidehithaware
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Introduction to Http Methods (GET, pUT,


POST, DELETE)
HTTP methods are the verbs used in HTTP requests to specify the desired action
on a resource. They are essential for building web applications and APIs. Here are
the four most common HTTP methods:

1. GET
Purpose: Retrieves data from a server.
Characteristics:
Idempotent: Multiple identical requests produce the same result.
Safe: Does not modify server-side resources.
Example:
Request: GET /users
Response: A list of all users.
2. POST
Purpose: Submits data to be processed by a server.
Characteristics:
Not idempotent: Multiple identical requests may produce different results.
Not safe: Modifies server-side resources.
Example:
Request: POST /users (with user data in the request body)
Response: A newly created user resource.
3. PUT
Purpose: Updates an existing resource on the server.
Characteristics:
Idempotent: Multiple identical requests produce the same result.
Example:
Request: PUT /users/123 (with updated user data in the request body)
Response: The updated user resource.
4. DELETE
Purpose: Deletes a resource from the server.
Characteristics:
Idempotent: Multiple identical requests produce the same result.
Example:
Request: DELETE /users/123
Response: A success message or an error message.
Key Points to Remember:
GET requests should never be used to modify data on the server.
POST requests are often used to create new resources or trigger actions.
PUT requests are used to update existing resources.
DELETE requests are used to remove existing resources.
By understanding these HTTP methods, you can effectively interact with
web servers and build robust web applications and APIs.
2

Web Services
Web Services: A Bridge Between Applications
A web service is a software application that uses standardized protocols to exchange data
with other applications over the internet. It's like a building block that allows different
applications to communicate and interact, regardless of their underlying technology or
platform.
Key Characteristics of Web Services:
Standardized Protocols: Web services rely on standard protocols like HTTP, SOAP, or REST
to ensure interoperability.
Data Formats: They commonly use data formats such as XML or JSON to exchange
information.
Remote Access: Web services can be accessed remotely over the internet.
Loose Coupling: The components of a web service are loosely coupled, allowing for flexibility
and modularity.
How Web Services Work:

Request: A client application sends a request to a web service, usually using HTTP.
Processing: The web service receives the request, processes it, and generates a response.
Response: The web service sends the response back to the client application.
Types of Web Services:
▪ SOAP (Simple Object Access Protocol): A protocol for exchanging information in a
structured format over HTTP.
▪ REST (Representational State Transfer): An architectural style for designing
networked applications, often used for building web APIs.
Real-World Examples of Web Services:
Weather APIs: Provide real-time weather information.
Payment Gateways: Process online payments.
Social Media APIs: Allow applications to interact with social media platforms.
Cloud Storage APIs: Enable access to cloud storage services.
Benefits of Web Services:
1. Interoperability: Web services can be used by applications built on different
platforms and programming languages.
2. Reusability: Web services can be reused in multiple applications.
3. Scalability: Web services can be scaled to handle increasing workloads.
4. Flexibility: Web services can be easily updated and modified.
5. By understanding the concept of web services, you can appreciate how they power
many of the applications we use daily, making our digital lives more connected and
efficient.
3

Introduction to REST Services?


Representational State Transfer (REST) is a software architectural style for
designing networked applications. It's a popular approach for building web
APIs, as it leverages the HTTP protocol to interact with resources.

Key Principles of REST:

Client-Server Architecture:
Clients and servers are separate entities.
Clients initiate requests, and servers process them and send responses.
Statelessness:
Each request from a client must contain all the information necessary to
understand and process the request.
The server does not store any client-specific state between requests.
Cache ability:
Responses can be cached to improve performance and reduce server load.
Responses should include cache control headers to indicate their cache
ability.
Uniform Interface:
A consistent interface is used for all interactions between clients and
servers.
This includes using standard HTTP methods (GET, POST, PUT, DELETE) and
media types (like JSON or XML) for data transfer.
Layered System:
The architecture can be layered, allowing for the addition of intermediaries
like load balancers or proxies.
Example: A RESTful API for a Blog

Consider a simple blog API that allows users to create, read, update, and
delete blog posts.

Resources:

/posts: Represents a collection of all blog posts.


/posts/{id}: Represents a specific blog post.
HTTP Methods and Actions:

GET /posts: Retrieves a list of all blog posts.


GET /posts/{id}`: Retrieves a specific blog post.
POST /posts: Creates a new blog post.
PUT /posts/{id}`: Updates an existing blog post.
**DELETE /posts/{id}`: Deletes a blog post.
Example Request:

GET /posts/123
Example Response:

JSON
4

{
"id": 123,
"title": "My First Blog Post",
"content": "This is the content of my first blog post.",
"author": "John Doe"
}
Use code with caution.

Benefits of REST:

1. Simplicity: RESTful APIs are relatively easy to understand and


implement.
2. Scalability: RESTful APIs can be scaled horizontally to handle
increasing load.
3. Flexibility: RESTful APIs can be used with a variety of programming
languages and platforms.
4. Performance: RESTful APIs can be optimized for performance by
using caching and other techniques.
By adhering to these principles, you can design and implement RESTful APIs
that are efficient, scalable, and maintainable.

Importance of REST in Service-Oriented/Microservices


Architecture:
1. Simplicity and Scalability: RESTful APIs are relatively simple to design
and implement. They are stateless, which makes them highly scalable
and suitable for distributed systems.
2. Flexibility: RESTful APIs can be easily consumed by a variety of
clients, including web applications, mobile apps, and other services.
3. Loose Coupling: RESTful services are loosely coupled, allowing for
independent development and deployment of services.
4. Interoperability: RESTful APIs use standard HTTP methods and data
formats, making them interoperable with different systems and
technologies.
5. Efficiency: RESTful APIs can be optimized for performance by using
caching and other techniques.

How REST Fits into Service-Oriented/Microservices Architecture:


In a service-oriented or microservices architecture, RESTful APIs are used
to expose the functionality of individual services. Each service can be
accessed via a well-defined RESTful interface, allowing other services or
client applications to interact with it. This enables:

1. Decentralized Development: Teams can work independently on


different services.
2. Flexible Integration: Services can be easily integrated with other
systems.
3. Scalability: Services can be scaled independently to meet changing
demands.
5

4. Resilience: Failures in one service can be isolated, minimizing impact


on the overall system.

Path Variables
In RESTful API design, path variables are placeholders within a URL that
allow for dynamic values to be inserted. They are enclosed in curly braces
{} and represent specific segments of the resource being requested.

Why Use Path Variables?


1. Identifying Specific Resources:
Example:
GET /users/{userId}
In this example, {userId} is a path variable. By replacing {userId} with a
specific user ID, you can retrieve information about that particular user.
2. Creating Dynamic URLs:
Example:
GET /products/{productId}/reviews
Here, {productId} is a path variable that allows you to fetch reviews for a
specific product.
3. Improving URL Readability:
Path variables can make URLs more human-readable and easier to
understand. For instance, /users/john_doe is more intuitive than
/users?username=john_doe.

How Path Variables Work:


▪ URL Matching: When a client sends a request to a REST API, the
server matches the incoming URL with defined endpoint patterns.
▪ Variable Extraction: If the URL contains path variables, the server
extracts their values from the matched URL segment.
▪ Parameter Binding: The extracted values are then bound to the
corresponding parameters in the server-side handler method.
Example in Spring MVC:

Java
@RestController
public class UserController {

@GetMapping("/users/{userId}")
public User getUser(@PathVariable Long userId) {
// Retrieve user information based on the userId
User user = [Link](userId);
return user;
}
}

In this example, the @PathVariable annotation is used to bind the


userId path variable to the userId parameter of the getUser method.
6

Request Body in REST: Sending Data to the Server

In a RESTful API, the request body is a section of an HTTP request that


contains data sent from the client to the server. This data is typically used
to create, update, or delete resources on the server.

The most common formats for request bodies are:


JSON (JavaScript Object Notation):
Lightweight and human-readable format.
Widely used in modern web applications.
Example:
JSON
{
"name": "John Doe",
"age": 30,
"city": "New York"
}

Postman and Insomnia: Popular API testing tools to interact with REST APIs,
sending requests and inspecting responses.
Implementing a Simple REST Service (Java with Spring Boot)
1. Project Setup:

Create a new Spring Boot project.


Add the spring-boot-starter-web dependency to your [Link] or build
configuration.
2. Controller Class:

Java
@RestController
public class MyController {

@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}

@PostMapping("/greet")
public String greet(@RequestBody GreetingRequest request) {
return "Hello, " + [Link]() + "!";
}
}
Use code with caution.

3. GreetingRequest Class:

Java
public class GreetingRequest {
7

private String name;

// Getters and setters


}
Use code with caution.

4. Testing with Postman or Insomnia

GET Request:

URL: [Link]
Method: GET
Expected Response: "Hello, World!"
POST Request:

URL: [Link]
Method: POST
Body: JSON format (e.g., {"name": "Alice"})
Header: Content-Type: application/json
Expected Response: "Hello, Alice!"
Key Points for Testing with Postman and Insomnia:
Environment Setup: Ensure you have a running Spring Boot application.
Base URL: Set the base URL in your testing tool to the address of your
running application.
Request Methods: Select the appropriate HTTP method (GET, POST, PUT,
DELETE).
Request Headers: Set necessary headers like Content-Type for JSON or
form-encoded requests.
Request Body: Construct the request body in the correct format (JSON,
form-encoded, etc.).
Response Inspection: Examine the response status code, headers, and body
to verify the correctness of the API response.
Authorization: If your API requires authentication, configure it in your
testing tool.
Parameterization: Use variables and scripts to parameterize your tests for
flexibility.
Test Suites and Collections: Organize your tests into suites and collections
for better management.

You might also like