Showing posts with label path parameter. Show all posts
Showing posts with label path parameter. Show all posts

Thursday, 19 March 2020

Swagger Editor: Adding template or path parameters to the API

Path parameters are used to bind segments of paths to method parameters. Suppose you want to get details of specific employee, usually the url look like following.

/employees/1: Gives you details of employee with id 1.
/employees/2: Givens you details of employee with id 2.

Example
paths:
  /employees/{employeeId}:
    get:
      parameters: 
      - in: path
        name: employeeId
        required: true
        schema:
          type: integer
          example: 123
      responses:
        200:
          description: Get Specific Employee Details
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                    example: 123
                  name:
                    type: string
                    example: Krishna

data.yaml
openapi: 3.0.0
info:
  title: Customer Data Aceess API
  description: API to expose all the CRUD operations on  customers
  contact:
    name: Krishna
    email: krishna123@abc.com
    url: https://self-learning-java-tutorial.blogspot.com/
  version: 1.0.0
paths:
  /employees/{employeeId}:
    get:
      parameters: 
      - in: path
        name: employeeId
        required: true
        schema:
          type: integer
          example: 123
      responses:
        200:
          description: Get Specific Employee Details
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                    example: 123
                  name:
                    type: string
                    example: krishna
  /employees:
      get:
        parameters: 
          - in: query
            name: from
            description: Page number to return
            required: true
            schema:
              type: integer
              example: 1
          - in: query
            name: size
            description: Number of elements to return
            required: false
            schema:
              type: integer
              example: 10
              minimum: 10
              maximum: 100
        responses:
          200:
            description: List of all the employees in organization
            content:
               application/json:
                  schema:
                    type: array
                    items:
                      properties:
                        id:
                          type: integer
                          example: 1234
                        name:
                          type: string
                          example: Krishna

Copy the content of data.yaml to Swagger Editor, you can see the API definition at right side of the window.

Previous                                                    Next                                                    Home

Wednesday, 7 August 2019

Spring boot REST: @PathVariable: Map path parameters to method arguments


@PathVariableannotation is used to bind segments of paths to method parameters. Suppose you want to get details of specific employee, usually the url look like following.

/employees/1: Gives you the details of employee with id 1.
/employees/2: Gives you the details of employee with id 2.

Example
@RequestMapping(value = "employees/{id}", method = RequestMethod.GET)
public ResponseEntity<Employee> byId(@PathVariable("id") int employeeId) {

  for (Employee emp : empRepo.all()) {
    if (emp.getId() == employeeId) {
      return ResponseEntity.ok(emp);
    }
  }
  return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new Employee());
}

In the above snippet. path variable "id" is mapped to employeeId.

Find the below working application.


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
  public static void main(String[] args) {

    SpringApplication.run(App.class, args);

  }
}


EmployeeController.java
package com.sample.app.cotroller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sample.app.model.Employee;
import com.sample.app.repository.EmployeeRepository;

@RestController
@RequestMapping("api/v1/")
public class EmployeeController {

  @Autowired
  private EmployeeRepository empRepo;

  @RequestMapping(value = "employees", method = RequestMethod.GET)
  public ResponseEntity<List<Employee>> all() {
    return ResponseEntity.ok(empRepo.all());
  }

  @RequestMapping(value = "employees", method = RequestMethod.POST)
  public ResponseEntity<Employee> create(@RequestBody Employee emp) {
    Employee persistedEmp = empRepo.add(emp);

    return ResponseEntity.status(HttpStatus.CREATED).body(persistedEmp);

  }

  @RequestMapping(value = "employees/{id}", method = RequestMethod.GET)
  public ResponseEntity<Employee> byId(@PathVariable("id") int employeeId) {

    for (Employee emp : empRepo.all()) {
      if (emp.getId() == employeeId) {
        return ResponseEntity.ok(emp);
      }
    }
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new Employee());
  }
}


HomeController.java
package com.sample.app.cotroller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

  @RequestMapping("/")
  public String home() {
    return "Hello World";
  }
}


Employee.java
package com.sample.app.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties({"employee_id"})
@JsonPropertyOrder({"last_name", "first_name"})
public class Employee {
  

  @JsonProperty("employee_id")
  private int id;

  @JsonProperty("first_name")
  private String firstName;

  @JsonProperty("last_name")
  private String lastName;
  
  public Employee() {}

  public Employee(int id, String firstName, String lastName) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
        .append(lastName).append("]");
    return builder.toString();
  }

}


EmployeeRepository.java
package com.sample.app.repository;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.sample.app.model.Employee;

@Repository
public class EmployeeRepository {

  private static final List<Employee> emps = new ArrayList<> ();
  
  private static int counter = 4;
  
  static {
    Employee emp1 = new Employee(1, "Sunil", "Dayanand");
    Employee emp2 = new Employee(2, null, "Shetty");
    Employee emp3 = new Employee(3, "Ram", "Anand");
    Employee emp4 = new Employee(4, "Akansha", null);
    
    emps.add(emp1);
    emps.add(emp2);
    emps.add(emp3);
    emps.add(emp4);
    
  }
  
  public List<Employee> all(){
    return emps;
  }
  
  public Employee add(Employee emp) {
    emp.setId(counter);
    counter++;
    
    emps.add(emp);
    return emp;
  }
  
}


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>springRest</groupId>
  <artifactId>springRest</artifactId>
  <version>1</version>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>

  <name>springbootApp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

  </dependencies>
</project>


Total project structure looks like below.

Run App.java.

Open the url ‘http://localhost:8080/api/v1/employees/1’ in browser to get employee 1 details.

{
  "last_name": "Dayanand",
  "first_name": "Sunil"
}

You can download complete working application from this link.




Previous                                                    Next                                                    Home