Skip to content

Commit e386bd4

Browse files
authoredAug 30, 2024
Merge pull request #15 from codeasarjun/rest
REST API has been added
2 parents fb05208 + 74fac23 commit e386bd4

File tree

4 files changed

+306
-0
lines changed

4 files changed

+306
-0
lines changed
 
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# What is REST?
2+
3+
REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on stateless, client-server communication and uses standard HTTP methods for interactions. Key principles of REST include:
4+
5+
- **Statelessness:** Each request from a client must contain all the information needed to process the request.
6+
- **Client-Server Architecture:** Separation of client and server responsibilities.
7+
- **Uniform Interface:** A consistent and uniform way of interacting with resources.
8+
- **Cacheability:** Responses must explicitly indicate whether they are cacheable.
9+
- **Layered System:** The API should be designed with layers, where each layer interacts only with the adjacent layer.
10+
11+
## HTTP Methods Used in REST
12+
13+
REST APIs use standard HTTP methods to perform operations on resources:
14+
15+
- **GET:** Retrieve data from the server.
16+
- **POST:** Create a new resource on the server.
17+
- **PUT:** Update an existing resource.
18+
- **DELETE:** Remove a resource from the server.
19+
- **PATCH:** Apply partial updates to a resource.
20+
21+
## Resources and Endpoints
22+
23+
- **Resource:** An entity or object that you interact with, such as a user or a product.
24+
- **Endpoint:** A specific URL where resources are accessed.
25+
26+
## Status Codes
27+
28+
HTTP status codes indicate the result of an API request:
29+
30+
- **200 OK:** The request was successful.
31+
- **201 Created:** A resource was successfully created.
32+
- **204 No Content:** The request was successful, but there's no content to return.
33+
- **400 Bad Request:** The request was invalid.
34+
- **401 Unauthorized:** Authentication is required or failed.
35+
- **403 Forbidden:** Access to the resource is denied.
36+
- **404 Not Found:** The requested resource was not found.
37+
- **500 Internal Server Error:** An error occurred on the server.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
{
2+
"openapi": "3.0.0",
3+
"info": {
4+
"title": "Task Management API",
5+
"version": "1.0.0",
6+
"description": "A simple API for managing tasks."
7+
},
8+
"servers": [
9+
{
10+
"url": "http://127.0.0.1:5000",
11+
"description": "Local server"
12+
}
13+
],
14+
"paths": {
15+
"/tasks": {
16+
"get": {
17+
"summary": "Get all tasks",
18+
"responses": {
19+
"200": {
20+
"description": "A list of tasks",
21+
"content": {
22+
"application/json": {
23+
"schema": {
24+
"type": "object",
25+
"properties": {
26+
"tasks": {
27+
"type": "array",
28+
"items": {
29+
"$ref": "#/components/schemas/Task"
30+
}
31+
}
32+
}
33+
}
34+
}
35+
}
36+
}
37+
}
38+
},
39+
"post": {
40+
"summary": "Create a new task",
41+
"requestBody": {
42+
"required": true,
43+
"content": {
44+
"application/json": {
45+
"schema": {
46+
"$ref": "#/components/schemas/NewTask"
47+
}
48+
}
49+
}
50+
},
51+
"responses": {
52+
"201": {
53+
"description": "The created task",
54+
"content": {
55+
"application/json": {
56+
"schema": {
57+
"$ref": "#/components/schemas/Task"
58+
}
59+
}
60+
}
61+
},
62+
"400": {
63+
"description": "Bad request"
64+
}
65+
}
66+
}
67+
},
68+
"/tasks/{taskId}": {
69+
"get": {
70+
"summary": "Get a task by ID",
71+
"parameters": [
72+
{
73+
"name": "taskId",
74+
"in": "path",
75+
"required": true,
76+
"schema": {
77+
"type": "integer",
78+
"example": 1
79+
}
80+
}
81+
],
82+
"responses": {
83+
"200": {
84+
"description": "A task",
85+
"content": {
86+
"application/json": {
87+
"schema": {
88+
"$ref": "#/components/schemas/Task"
89+
}
90+
}
91+
}
92+
},
93+
"404": {
94+
"description": "Task not found"
95+
}
96+
}
97+
},
98+
"put": {
99+
"summary": "Update a task by ID",
100+
"parameters": [
101+
{
102+
"name": "taskId",
103+
"in": "path",
104+
"required": true,
105+
"schema": {
106+
"type": "integer",
107+
"example": 1
108+
}
109+
}
110+
],
111+
"requestBody": {
112+
"required": true,
113+
"content": {
114+
"application/json": {
115+
"schema": {
116+
"$ref": "#/components/schemas/Task"
117+
}
118+
}
119+
}
120+
},
121+
"responses": {
122+
"200": {
123+
"description": "The updated task",
124+
"content": {
125+
"application/json": {
126+
"schema": {
127+
"$ref": "#/components/schemas/Task"
128+
}
129+
}
130+
}
131+
},
132+
"404": {
133+
"description": "Task not found"
134+
},
135+
"400": {
136+
"description": "Bad request"
137+
}
138+
}
139+
},
140+
"delete": {
141+
"summary": "Delete a task by ID",
142+
"parameters": [
143+
{
144+
"name": "taskId",
145+
"in": "path",
146+
"required": true,
147+
"schema": {
148+
"type": "integer",
149+
"example": 1
150+
}
151+
}
152+
],
153+
"responses": {
154+
"200": {
155+
"description": "Task successfully deleted"
156+
},
157+
"404": {
158+
"description": "Task not found"
159+
}
160+
}
161+
}
162+
}
163+
},
164+
"components": {
165+
"schemas": {
166+
"Task": {
167+
"type": "object",
168+
"properties": {
169+
"id": {
170+
"type": "integer",
171+
"example": 1
172+
},
173+
"title": {
174+
"type": "string",
175+
"example": "Buy groceries"
176+
},
177+
"done": {
178+
"type": "boolean",
179+
"example": false
180+
}
181+
}
182+
},
183+
"NewTask": {
184+
"type": "object",
185+
"required": ["title"],
186+
"properties": {
187+
"title": {
188+
"type": "string",
189+
"example": "Read a book"
190+
}
191+
}
192+
}
193+
}
194+
}
195+
}
196+

‎additional-materials/RESTAPI/app.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from flask import Flask, jsonify, request
2+
3+
app = Flask(__name__)
4+
5+
tasks = [
6+
{'id': 1, 'title': 'Buy groceries', 'done': False},
7+
{'id': 2, 'title': 'Learn Python', 'done': True}
8+
]
9+
10+
# get all tasks
11+
@app.route('/tasks', methods=['GET'])
12+
def get_tasks():
13+
return jsonify({'tasks': tasks})
14+
15+
# get a single task
16+
@app.route('/tasks/<int:task_id>', methods=['GET'])
17+
def get_task(task_id):
18+
task = next((task for task in tasks if task['id'] == task_id), None)
19+
if task is None:
20+
return jsonify({'error': 'Task not found'}), 404
21+
return jsonify({'task': task})
22+
23+
# create a new task
24+
@app.route('/tasks', methods=['POST'])
25+
def create_task():
26+
if not request.json or 'title' not in request.json:
27+
return jsonify({'error': 'Bad request'}), 400
28+
task = {
29+
'id': tasks[-1]['id'] + 1,
30+
'title': request.json['title'],
31+
'done': False
32+
}
33+
tasks.append(task)
34+
return jsonify({'task': task}), 201
35+
36+
# update an existing task
37+
@app.route('/tasks/<int:task_id>', methods=['PUT'])
38+
def update_task(task_id):
39+
task = next((task for task in tasks if task['id'] == task_id), None)
40+
if task is None:
41+
return jsonify({'error': 'Task not found'}), 404
42+
if not request.json:
43+
return jsonify({'error': 'Bad request'}), 400
44+
task['title'] = request.json.get('title', task['title'])
45+
task['done'] = request.json.get('done', task['done'])
46+
return jsonify({'task': task})
47+
48+
# delete a task
49+
@app.route('/tasks/<int:task_id>', methods=['DELETE'])
50+
def delete_task(task_id):
51+
global tasks
52+
tasks = [task for task in tasks if task['id'] != task_id]
53+
return jsonify({'result': 'Task deleted'})
54+
55+
if __name__ == '__main__':
56+
app.run(debug=True)
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import requests
2+
3+
# get all tasks
4+
response = requests.get('http://127.0.0.1:5000/tasks')
5+
print(response.json())
6+
7+
# create a new task
8+
response = requests.post('http://127.0.0.1:5000/tasks', json={'title': 'Read a book'})
9+
print(response.json())
10+
11+
# update a task
12+
response = requests.put('http://127.0.0.1:5000/tasks/1', json={'title': 'Buy groceries', 'done': True})
13+
print(response.json())
14+
15+
# delete a task
16+
response = requests.delete('http://127.0.0.1:5000/tasks/2')
17+
print(response.json())

0 commit comments

Comments
 (0)
Please sign in to comment.