spring-boot
|

Tạo Rest API đơn giản với Spring boot

Xin chào các bạn, hôm nay mình sẽ hướng dẫn các bạn tạo một Rest API đơn giản với Spring boot.

Tạo project

Các bạn mở IDE Interlij lên vào tạo project như sau:

Rest API với Spring boot
Rest API với Spring boot

Nếu bạn chưa biết cách tạo project bằng Spring Assistant plugin thì có thể xem bài viết của mình tại đây.

FIle build.gradle cho các bạn

plugins {
	id 'org.springframework.boot' version '2.2.4.RELEASE'
	id 'io.spring.dependency-management' version '1.0.9.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
	developmentOnly
	runtimeClasspath {
		extendsFrom developmentOnly
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

 

Xây dựng Rest API

Cấu trúc project như sau:

Rest API với Spring boot
Rest API với Spring boot

Class RestApiApplication: Đây là class chính để khởi chạy Spring boot

package com.learnspringboot.demo;

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

@SpringBootApplication
public class RestApiApplication {

	public static void main(String[] args) {
		SpringApplication.run(RestApiApplication.class, args);
	}

}

 

Class  RestController: Đây chính là class

package com.learnspringboot.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RestController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<String> home(){
        return new ResponseEntity<>("Welcome to home page", HttpStatus.OK);
    }
}

 

Class RestController được chú thích với Annotation @Controller

Annotation @RequestMapping dùng để

Bây giờ chúng ta sẽ build project, mặc định thì spring boot sẽ chạy ở cổng 8080.

Rest API với Srping boot
Rest API với Srping boot

Bây giờ chúng ta có thể dùng ứng dụng Postman để kiểm tra API của chúng ta

Rest API với Srping boot
Rest API với Spring boot

Bây giờ nếu bạn muốn đổi cổng của spring boot thì vào file application.properties và thêm script sau:

server.port = 9090

Mình để mã nguồn ở đây các bạn có thể tham khảo: https://github.com/tamvo-dev/rest-api.git

Nếu trong quá trình làm các bạn gặp khó khăn gì thì đừng ngại comment phía dưới cho mình biết nhé. Bài viết của mình đến đây là kết thúc, cám ơn các bạn đã theo dõi !

Similar Posts

Subscribe
Notify of
guest
0 Bình luận
Inline Feedbacks
View all comments