-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGET API & POST API..
More file actions
461 lines (337 loc) · 12.4 KB
/
Copy pathGET API & POST API..
File metadata and controls
461 lines (337 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
Building Your First GET API..
Imagine you are building an app that manages users. Your app needs to send user information to other parts of the app or even other applications.
In this demo, we created a UserController with several endpoints to:
Get individual users (Alice, Bob, Charlie)
Get a list of all users
This is exactly how real-world APIs work—you request data from a URL, and the server sends it back as JSON.
Before we begin :
Run the application.
The API Tester will open automatically.
Enter below URL one by one -> Click on "Call API" and Observe the Resopnse
/api/users/alice
/api/users/bob
/api/users/charlie
/api/users/all
Let’s break down how this code works step by step.
How the Code Works
1. Class-level annotations
@RestController
@RequestMapping("/api/users")
@RestController → Marks the class as a controller for APIs.
@RequestMapping("/api/users") → Sets a base URL for all APIs in this controller.
Every method in this class will start with /api/users.
2. Single user endpoints
@GetMapping("/alice")
@GetMapping("/bob")
@GetMapping("/charlie")
@GetMapping maps a specific URL → method.
Examples:
/api/users/alice → calls getAlice() → returns Alice’s info
/api/users/bob → calls getBob() → returns Bob’s info
/api/users/charlie → calls getCharlie() → returns Charlie’s info
3. List of users endpoint
@GetMapping("/all")
public List<User> getAllUsers()
Returns a list of User objects.
Spring Boot automatically converts Java objects → JSON array.
Example URL: /api/users/all → Returns:
[
{ "name": "Alice", "email": "alice@example.com" },
{ "name": "Bob", "email": "bob@example.com" },
{ "name": "Charlie", "email": "charlie@example.com" }
]
#########################################
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Arrays;
@RestController
@RequestMapping("/api/users")
public class UserController {
// GET /api/users/alice
@GetMapping("/alice")
public User getAlice() {
return new User("Alice", "alice@example.com");
}
// GET /api/users/bob
@GetMapping("/bob")
public User getBob() {
return new User("Bob", "bob@example.com");
}
// GET /api/users/charlie
@GetMapping("/charlie")
public User getCharlie() {
return new User("Charlie", "charlie@example.com");
}
// GET /api/users/all
@GetMapping("/all")
public List<User> getAllUsers() {
return Arrays.asList(
new User("Alice", "alice@example.com"),
new User("Bob", "bob@example.com"),
new User("Charlie", "charlie@example.com")
);
}
}
// User class
class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() { return name; }
public String getEmail() { return email; }
}
###########################################
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Arrays;
@RestController
@RequestMapping("/api/fruits")
public class FruitController {
// TODO 1: Create an endpoint to return Apple
@GetMapping("/apple")
public Fruit getApple() {
// Return a Fruit object with name "Apple" and taste "Sweet"
return new Fruit("Apple", "Sweet");
}
// TODO 2: Create an endpoint to return Banana
@GetMapping("/banana")
public Fruit getBanana() {
// Return a Fruit object with name "Banana" and taste "Sweet"
return new Fruit("Banana", "Sweet");
}
// TODO 3: Create an endpoint to return Lemon
@GetMapping("/lemon")
public Fruit getLemon() {
// Return a Fruit object with name "Lemon" and taste "Sour"
return new Fruit("Lemon", "Sour");
}
// TODO 4: Create an endpoint to return a list of all fruits
@GetMapping("/all")
public List<Fruit> getAllFruits() {
return Arrays.asList(
new Fruit("Apple", "Sweet"),
new Fruit("Banana", "Sweet"),
new Fruit("Lemon", "Sour")
);
}
}
// Fruit class (already completed)
class Fruit {
private String name;
private String taste;
public Fruit(String name, String taste) {
this.name = name;
this.taste = taste;
}
public String getName() { return name; }
public String getTaste() { return taste; }
}
################################
Guess the Output
Which annotation is used in Spring Boot to create a GET API endpoint?
ANSWER = @GetMapping
@GetMapping is used in Spring Boot to create GET API endpoints, which are meant to retrieve data from the server.
The other annotations are used for different operations like creating, updating, or deleting data.
##############################
GET API - Identify Response Format
What is the default response format of a GET API when using @RestController?
ANSWER = JSON
@RestController automatically converts Java objects into JSON responses.
##################################
.................. NOW POST API ...........................
##############################
Building Your First POST API..
Imagine you are building an app to manage users. You want to let clients (frontend apps, Postman, etc.) add new users to your system.
In this demo, we created a UserController with an endpoint to:
Add a single user
This is exactly how real-world APIs work — you send JSON to a URL, the server receives it, stores it, and responds with a confirmation message.
Note: There is also a GET endpoint available to see which users have been added for your better understanding, but we will not focus on GET here.
Before we begin :
Run the application.
The API Tester will open automatically.
Send JSON to the following URLs and observe the response:
Example Request
POST – Add single user
POST : /users
{
"name": "David",
"email": "david@example.com"
}
Response:
"User added successfully!"
How the Code Works
Single user POST endpoint
@PostMapping
public String addUser(@RequestBody User user) {
users.add(user);
return "User added successfully!";
}
@PostMapping → Maps the URL /users to this method.
@RequestBody → Converts incoming JSON into a Java User object automatically.
users.add(user) → Adds the user to the in-memory list.
Return message → Sends a confirmation string back to the client.
Key Points
POST APIs → Used to send data to the server.
@RequestBody → Automatically converts JSON → Java objects.
We'll see @RequestBody later in detail.
For Testing :
After sending your POST request, you can select GET and type /users in your API tester* to see whether your user has been added successfully.
#######################################
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
// In-memory list to store users
private List<User> users = new ArrayList<>();
// GET API - fetch all users
@GetMapping
public List<User> getUsers() {
return users;
}
// POST API - add a new user
@PostMapping
public String addUser(@RequestBody User user) {
users.add(user);
return "User added successfully!";
}
}
/* -------- User Class (inside same file) -------- */
class User {
private String name;
private String email;
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
#############################################3
Practice Problem - Todo App (POST API)
Instructions:
Complete your code first.
Click on "Run" to start the server and make sure it runs correctly.
If you make any changes to the code after running, you must run the server again.
Only after running the server with the latest changes, your submission will reflect the updated solution.
Do not submit if the server is not running; otherwise, your solution will fail.
Goal :
The goal of this exercise is to practice creating a POST API in Spring Boot.
Your Task :
Build simple Todo application. The application should allow clients (like frontend apps or Postman) to:
Add a new todo via POST API.
Fetch all todos via GET API (for testing only).
Implement the POST API that will take a JSON object representing a Todo and store it in an in-memory list.
Example JSON for POST request:
Select POST and add JSON request
{
"title": "Buy groceries",
"completed": false
}
After adding a todo, the API should return a confirmation message like:
"Todo added successfully"
Note:
The GET API is already implemented to see all added todos, but your focus is on implementing the POST API.
#########################################
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/todos")
public class TodoController {
// In-memory list to store todos
private List<Todo> todos = new ArrayList<>();
// GET API - fetch all todos
@GetMapping
public List<Todo> getTodos() {
return todos;
}
// POST API - add new todo (starter template)
@PostMapping
public String addTodo(@RequestBody Todo todo) {
// Your code here
todos.add(todo);
return "Todo added successfully";
}
}
// Todo class to represent the data
class Todo {
private String title;
private boolean completed;
// Getters and Setters
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
##################################################
Guess the Output
Which annotation is used in Spring Boot to create a POST API endpoint?
ANSWER = @PostMapping
@PostMapping is used to handle HTTP POST requests, usually to send or create data.
#############################
Identify the Purpose
What is the main purpose of a POST API?
ANSWER = Create or submit data
POST APIs are mainly used to send data to the server for creation or processing.
####################################
THEORY ......
###########################
GET vs POST....
Till now, you have worked with both GET and POST APIs in Spring Boot. This section is a quick and clear recap to reinforce what you already practiced.
Now let’s clearly understand how they are different and when to use which.
What is the purpose?image
How is data sent?
GET API
Used to fetch data from Backend..
Only reads data..
Does not change anything on the server...
Data is sent as part of the request URL
The client requests information using a URL
POST API
Used to send data to the Backend..
Used to create or submit data..
Can change data on the server..
Data is sent in the request body
Usually in JSON format
Spring Boot Annotations
GET = @GetMapping
POST = @PostMapping
Simple rule to remember
If you are getting data → use GET
If you are sending data → use POST
Now that you know how requests work, let’s learn how Spring Boot receives input data.
###############################
Answer In Short
Scenario : Fetching Data
You are building a backend API for an application that manages users. A frontend application (such as a web or mobile app) needs to display a list of all users on the screen.
The frontend sends a request to the server only to read existing data.
Question:
Which HTTP method should you use — GET or POST? Why?
ANSWER = GET
get api only read data , don't change anything
#################################
Answer In Short
Scenario : Creating Data
You are building a user registration feature for an application. A frontend screen contains a registration form where users enter details such as name, email, and password.
When the user clicks the Register button, the frontend sends these details to the backend server. The backend’s responsibility is to process the received data and create a new user record in the system
Each time the request is sent, a new user should be created.
Question:
Which HTTP method is more appropriate — GET or POST? Why?
ANSWER = post
each time data is modified