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

Mastering Java Logging: A Guide to Debug, Info, Warn, and Error Levels

Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Logging is an essential aspect of application development and maintenance. It helps developers track application behavior and troubleshoot issues effectively. Java provides various logging levels to categorize messages based on their severity and purpose. This article covers all major logging levels: Trace , Debug , Info , Warn , Error , and Fatal , along with how these levels impact log printing. 1. Trace The Trace level is the most detailed logging level. It is typically used for granular debugging, such as tracking every method call or step in a complex computation. Use this level sparingly, as it can generate a large volume of log data. 2. Debug The Debug level provides detailed information useful during dev...

Choosing Between Envoy and NGINX Ingress Controllers for Kubernetes

As Kubernetes has become the standard for deploying containerized applications, ingress controllers play a critical role in managing how external traffic is routed to services within the cluster. Envoy and NGINX are two of the most popular options for ingress controllers, and each has its strengths, weaknesses, and ideal use cases. In this blog, we’ll explore: How both ingress controllers work. A detailed comparison of their features. When to use Envoy vs. NGINX for ingress management. What is an Ingress Controller? An ingress controller is a specialized load balancer that: Manages incoming HTTP/HTTPS traffic. Routes traffic to appropriate services based on rules defined in Kubernetes ingress resources. Provides features like TLS termination, path-based routing, and host-based routing. How Envoy Ingress Controller Works Envoy , initially built by Lyft, is a high-performance, modern service proxy and ingress solution. Here's how it operates in Kubernetes: Ingress Resource : You d...

How to Identify High-Growth Stocks: Key Metrics and Analysis

Identifying high-growth stocks can significantly enhance your investment portfolio's performance. By analyzing key financial metrics, growth indicators, and market opportunities, you can pinpoint companies with the potential for exceptional returns. This blog outlines the critical factors to consider when selecting high-growth stocks. Key Metrics for High-Growth Stocks 1. Earnings Growth Consistent earnings growth is a hallmark of high-growth stocks. Look for companies with a double-digit EPS (Earnings Per Share) growth rate over several years, indicating strong profitability. 2. Revenue Growth Revenue growth shows the company’s ability to expand its market share or increase sales. Look for annual revenue growth rates above 15-20% . 3. Return on Equity (ROE) ROE measures how effectively a company uses shareholders' equity to generate profit. A high ROE (above 15-20% ) is ideal for high-growth companies. 4. Profit Margins Gross...