Skip to main content

Understanding API Parameters in Spring Boot

Understanding API Parameters in Spring Boot

When designing APIs in Spring Boot, it's essential to understand how to handle different types of parameters. These parameters define how data is sent from the client to the server. Let's break down the common types of parameters used in API development, with examples and cURL commands.

1. Types of Parameters

Parameter Type Location Use Case Example Format Annotation in Spring Boot
Query Param URL after `?` Filtering, Pagination ?key=value @RequestParam
Path Param In the URL path Identifying specific resource /resource/{id} @PathVariable
Form Param Form-encoded body Simple form submissions key=value @RequestParam
Request Body JSON or raw data in body Complex objects or large payloads JSON or XML @RequestBody

2. Examples

1. Query Parameters


@GetMapping("/api/products")
public ResponseEntity<List<Product>> getProducts(@RequestParam String category) {
    return ResponseEntity.ok(productService.getProducts(category));
}
    

cURL:

curl -X GET "http://localhost:8080/api/products?category=electronics"

2. Path Parameters


@GetMapping("/api/products/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
    return ResponseEntity.ok(productService.getProductById(id));
}
    

cURL:

curl -X GET "http://localhost:8080/api/products/123"

3. Form Parameters


@PostMapping("/api/products")
public ResponseEntity<Product> createProduct(@RequestParam String name, @RequestParam double price) {
    return ResponseEntity.ok(productService.createProduct(name, price));
}
    

cURL:

curl -X POST "http://localhost:8080/api/products" -d "name=phone&price=50000"

4. Request Body (JSON)


@PostMapping("/api/products")
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
    return ResponseEntity.ok(productService.createProduct(product));
}
    

cURL:

curl -X POST "http://localhost:8080/api/products" -H "Content-Type: application/json" -d '{"name":"phone","price":50000}'

Conclusion

Understanding how to handle query, path, form, and body parameters is essential for building robust APIs in Spring Boot. By selecting the right parameter type for the right scenario, you can create efficient, scalable, and well-structured applications.

Support us

Comments

Popular posts from this blog

Learning How to Map One-to-Many Relationships in JPA Spring Boot with PostgreSQL

  Introduction In this blog post, we explore how to effectively map one-to-many relationships using Spring Boot and PostgreSQL. This relationship type is common in database design, where one entity (e.g., a post) can have multiple related entities (e.g., comments). We'll dive into the implementation details with code snippets and provide insights into best practices. Understanding One-to-Many Relationships A one-to-many relationship signifies that one entity instance can be associated with multiple instances of another entity. In our case: Post Entity : Represents a blog post with fields such as id , title , content , and a collection of comments . Comment Entity : Represents comments on posts, including fields like id , content , and a reference to the post it belongs to. Mapping with Spring Boot and PostgreSQL Let's examine how we define and manage this relationship in our Spring Boot application: Post Entity  @Entity @Getter @Setter @Builder @AllArgsConstructor @NoArgsCon...

Understanding the Advertisement Domain: A Comprehensive Overview Part 2

 The advertisement domain is a complex and dynamic ecosystem that involves various technologies and platforms working together to deliver ads to users in a targeted and efficient manner. The primary goal is to connect advertisers with their target audience, increasing brand visibility, user engagement, and revenue generation. In this blog, we will delve into the different components of the advertisement ecosystem, key concepts like programmatic advertising and real-time bidding (RTB), and provide a practical example to illustrate how it all works. Key Components of the Advertisement Domain The advertisement domain broadly consists of the following components: Advertisers : These are brands or companies that want to promote their products or services through advertisements. They set up ad campaigns targeting specific user segments. Publishers : These are websites, mobile apps, or digital platforms that display ads to users. Publishers monetize their content by selling ad space to ad...

Tree Based Common problems and patterns

  Find the height of the tree. public class BinaryTreeHeight { public static int heightOfBinaryTree (TreeNode root) { if (root == null ) { return - 1 ; // Height of an empty tree is -1 } int leftHeight = heightOfBinaryTree(root.left); int rightHeight = heightOfBinaryTree(root.right); // Height of the tree is the maximum of left and right subtree heights plus 1 for the root return Math.max(leftHeight, rightHeight) + 1 ; } Find the Level of the Node. private static int findLevel (TreeNode root, TreeNode node, int level) { if (root == null ) { return - 1 ; // Node not found, return -1 } if (root == node) { return level; // Node found, return current level } // Check left subtree int leftLevel = findLevel(root.left, node, level + 1 ); if (leftLevel != - 1 ) { return leftLevel; // Node found ...