Implement a REST API with Python Modules
We will use Python's Flask framework to implement a simple REST API. Flask is a lightweight web framework that is well suited to quickly building web applications and RESTful APIs.
Example
from
flask
import
Flask
,
jsonify
,
request
app
=
Flask
(
name
)
Sample data
books
=
[
{
"id"
:
1
,
"title"
:
"1984"
,
"author"
:
"George Orwell"
}
,
{
"id"
:
2
,
"title"
:
"To Kill a Mockingbird"
,
"author"
:
"Harper Lee"
}
,
{
"id"
:
3
,
"title"
:
"The Great Gatsby"
,
"author"
:
"F. Scott Fitzgerald"
}
]
Get all books
@
app.
route
(
'/books'
,
methods
=
[
'GET'
]
)
def
get_books
(
)
:
return
jsonify
(
books
)
Get a specific book
@
app.
route
(
'/books/'
,
methods
=
[
'GET'
]
)
def
get_book
(
book_id
)
:
book
=
next
(
(
book
for
book
in
books
if
book
[
'id'
]
==
book_id
)
,
None
)
if
book:
return
jsonify
(
book
)
else
:
return
jsonify
(
{
"error"
:
"Book not found"
}
)
,
404
Add a new book
@
app.
route
(
'/books'
,
methods
=
[
'POST'
]
)
def
add_book
(
)
:
new_book
=
request.
get_json
(
)
books.
append
(
new_book
)
return
jsonify
(
new_book
)
,
201
Update book information
@
app.
route
(
'/books/'
,
methods
=
[
'PUT'
]
)
def
update_book
(
book_id
)
:
book
=
next
(
(
book
for
book
in
books
if
book
[
'id'
]
==
book_id
)
,
None
)
if
book:
updated_data
=
request.
get_json
(
)
book.
update
(
updated_data
)
return
jsonify
(
book
)
else
:
return
jsonify
(
{
"error"
:
"Book not found"
}
)
,
404
Delete a book
@
app.
route
(
'/books/'
,
methods
=
[
'DELETE'
]
)
def
delete_book
(
book_id
)
:
global
books
books
=
[
book
for
book
in
books
if
book
[
'id'
]
!=
book_id
]
return
jsonify
(
{
"result"
:
"Book deleted"
}
)
if
name
==
'main'
:
app.
run
(
debug
=
True
)
Code analysis:
- We first import the Flask framework and the related modules.
- Create a Flask application instance
app。 - Define sample data
books, which is a list containing book information. - Use
@app.routeThe decorator defines four routes:
/books (GET): get all books./books/ (GET): get a specific book./books (POST): add a new book./books/ (PUT): update book information./books/ (DELETE): delete a book.- In each route handler we use the
jsonifyfunction to convert the data to JSON format and return it. - Finally, use
app.run(debug=True)to start the Flask application with debug mode enabled.
Output: after running this code, the Flask application starts locally and listens on http://127.0.0.1:5000/by default. You can use tools such as Postman or curl to test these API endpoints. For example:
- Get all books:
GET http://127.0.0.1:5000/books - Get a specific book:
GET http://127.0.0.1:5000/books/1 - Add a new book:
POST http://127.0.0.1:5000/booksand provide JSON data in the request body. - Update book information:
PUT http://127.0.0.1:5000/books/1and provide the updated JSON data in the request body. - Delete a book:
DELETE http://127.0.0.1:5000/books/1
Python3 Examples