REST API (Representational State Transfer Application Programming Interface) is a way of building web services that allow clients to interact with servers over the internet. In this tutorial, we will be using Python and the Flask library to create a REST API.
Flask is a micro web framework for Python that allows you to easily build web applications. It is lightweight and simple to use, making it the perfect choice for building REST APIs. In this tutorial, we will be creating a simple REST API that allows clients to perform CRUD operations (Create, Read, Update, Delete) on a list of users.
To get started, you will need to have Python installed on your computer. You can download Python from https://www.python.org/downloads/. Once you have Python installed, you can install Flask using the following command:
pip install Flask
Once Flask is installed, create a new Python file called app.py
and open it in your favorite text editor. In this file, we will define our Flask application and create the endpoints for our REST API.
First, import the necessary modules:
from flask import Flask, jsonify, request
Next, create a new instance of the Flask class:
app = Flask(__name__)
Now, let’s define a list of users that we will use in our REST API:
users = [
{'id': 1, 'name': 'John Doe'},
{'id': 2, 'name': 'Jane Smith'}
]
Next, let’s create the endpoint for getting all users:
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users)
This endpoint will return a JSON representation of the list of users when the client makes a GET
request to /users
.
Next, let’s create the endpoint for getting a specific user by their ID:
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = [user for user in users if user['id'] == user_id]
if len(user) == 0:
return jsonify({'error': 'User not found'}), 404
return jsonify(user[0])
This endpoint will return a JSON representation of the user with the specified ID when the client makes a GET
request to /users/<user_id>
.
Next, let’s create the endpoint for adding a new user:
@app.route('/users', methods=['POST'])
def add_user():
data = request.get_json()
if 'name' not in data:
return jsonify({'error': 'Missing name parameter'}), 400
new_user = {
'id': len(users) + 1,
'name': data['name']
}
users.append(new_user)
return jsonify(new_user), 201
This endpoint will add a new user to the list of users when the client makes a POST
request to /users
.
Next, let’s create the endpoint for updating a user by their ID:
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
user = [user for user in users if user['id'] == user_id]
if len(user) == 0:
return jsonify({'error': 'User not found'}), 404
data = request.get_json()
user[0]['name'] = data.get('name', user[0]['name'])
return jsonify(user[0])
This endpoint will update the user with the specified ID when the client makes a PUT
request to /users/<user_id>
.
Finally, let’s create the endpoint for deleting a user by their ID:
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
user = [user for user in users if user['id'] == user_id]
if len(user) == 0:
return jsonify({'error': 'User not found'}), 404
users.remove(user[0])
return jsonify({'message': 'User deleted'})
This endpoint will delete the user with the specified ID when the client makes a DELETE
request to /users/<user_id>
.
To run the Flask application, add the following code at the bottom of the app.py
file:
if __name__ == '__main__':
app.run(debug=True)
To test the REST API, start the Flask application by running the following command in the terminal:
python app.py
You can now use a tool like Postman or cURL to make requests to the endpoints we created. For example, you can make a GET
request to http://localhost:5000/users
to get all users, or a POST
request to http://localhost:5000/users
to add a new user.
In this tutorial, we have created a simple REST API using Python and the Flask library. You can extend this API by adding more endpoints and functionality to suit your needs. Flask provides a powerful and flexible framework for building REST APIs, making it a great choice for web development projects.
mam zainstalowana wtyczke rest a mimo to końcówka .http nie działa
@jak nauczyć się programowania Po co pokazałeś możliwość zmiany portu ?
Po co robi się takie zmiany i do czego służą?
Jeśli masz gdzieś bardziej rozwinięty temat i możesz polecić linka chętnie skorzystam.
Świetne wprowadzenie. Dzięki!
Plik http jest u mnie w VSC widoczny jako zwykły plik txt, oraz nie mam send request. Pracuję na windows. Czy to kwestia systemu?
Świetne tutoriale 🙂 Jeżeli chodzi o Windowsa to te wtyczki, biblioteki, moduły i inne tego typu frameworki (załóżmy Django i Flask) instaluje się ze strony Pythona, czy w VS Code mamy możliwość doinstalowania ich? Wiem, że w PyCharm możemy np. Django zainstalować i innego rodzaju wtyczki niezbędne do pracy w Pythonie.
super tutorial 👍👍👍 byle do wtorku!
I znowu pierwszy 🙂