What is restful api in python with example

Peter 115 Published: 09/02/2024

What is restful api in python with example

Restful API!

A RESTful API (Representational State of Resources) is a web service that uses the REST (Representational State of Resources) architecture style to manipulate and retrieve resources. In Python, you can use popular libraries like Flask or Django to build a Restful API.

Here's an example using Flask:

from flask import Flask, jsonify, request

app = Flask(name)

A list of books

books = [

{'id': 1, 'title': 'Book One', 'author': 'John Doe'},

{'id': 2, 'title': 'Book Two', 'author': 'Jane Smith'},

{'id': 3, 'title': 'Book Three', 'author': 'Bob Johnson'}

]

Get all books

@app.route('/books', methods=['GET'])

def get_all_books():

return jsonify(books)

Get a book by ID

@app.route('/books/int:book_id', methods=['GET'])

def get_book(book_id):

for book in books:

if book['id'] == book_id:

return jsonify(book)

return jsonify({'error': 'Book not found'}), 404

Create a new book

@app.route('/books', methods=['POST'])

def create_book():

new_book = {

'id': len(books) + 1,

'title': request.json['title'],

'author': request.json['author']

}

books.append(new_book)

return jsonify(new_book), 201

Update a book

@app.route('/books/int:book_id', methods=['PUT'])

def update_book(book_id):

for book in books:

if book['id'] == book_id:

book['title'] = request.json.get('title', book['title'])

book['author'] = request.json.get('author', book['author'])

return jsonify(book)

return jsonify({'error': 'Book not found'}), 404

Delete a book

@app.route('/books/int:book_id', methods=['DELETE'])

def delete_book(book_id):

for i, book in enumerate(books):

if book['id'] == book_id:

del books[i]

return jsonify({'message': 'Book deleted'}), 200

return jsonify({'error': 'Book not found'}), 404

if name == 'main':

app.run(debug=True)

In this example:

We define a list of books with dictionaries representing each book. We have five endpoints: /books: Returns a JSON array of all books (GET). /books/<int:book_id>: Returns a specific book by ID (GET). /books: Creates a new book with the provided title and author (POST). /books/<int:book_id>: Updates an existing book's title and author (PUT). /books/<int:book_id>: Deletes a book by ID (DELETE).

This is a simple example, but you can imagine how this structure can be extended to handle more complex scenarios.

In Flask, we use the @app.route() decorator to define each endpoint. We then specify the HTTP methods allowed for that endpoint (GET, POST, PUT, DELETE). The request object allows us to access the request data, such as JSON bodies or query parameters.

This is just a taste of how you can build a Restful API in Python using Flask!

REST API in Python w3schools

Here's a detailed guide on creating a REST API using Python:

What is a REST API?

REST (Representational State of Resource) is an architectural style for designing networked applications. It's based on HTTP and uses verbs like GET, POST, PUT, and DELETE to operate on resources.

Why use Python for building REST APIs?

Python is a popular choice for building REST APIs due to its simplicity, ease of use, and extensive libraries. With Python, you can create robust, scalable, and maintainable APIs quickly.

Tools needed:

Python: You need to have Python installed on your machine (any version above 3.x will work). Flask: Flask is a lightweight Python web framework that's perfect for building REST APIs. Pip: Pip is the package installer for Python, which you'll use to install Flask and other dependencies.

Step-by-Step Guide:

1. Install Flask:

Open your terminal or command prompt and type the following:

pip install flask

This will download and install Flask on your machine.

2. Create a new project directory:

Create a new directory for your project, and navigate into it in your terminal or command prompt.

mkdir my_api

cd my_api

3. Create the API file:

In this directory, create a new file called app.py. This is where you'll write your Flask code.

# app.py

from flask import Flask, jsonify, request

app = Flask(name)

Sample data for testing purposes

data = [

{"id": 1, "name": "John"},

{"id": 2, "name": "Jane"}

]

@app.route('/users', methods=['GET'])

def get_users():

return jsonify(data)

@app.route('/users/int:user_id', methods=['GET'])

def get_user(user_id):

for user in data:

if user['id'] == user_id:

return jsonify(user)

return jsonify({"message": "User not found"}), 404

if name == 'main':

app.run(debug=True, port=5000)

In this code:

We import Flask and other necessary modules. We create a new instance of the Flask class, passing in our application's name (__name__). We define two routes: /users for retrieving all users, and /users/<int:user_id> for retrieving a specific user by ID. In each route function, we use Flask's jsonify function to return JSON data. 4. Run the API:

Run your API by executing the following command in your terminal or command prompt:

python app.py

This will start your Flask server on port 5000 (adjust this as needed).

5. Test the API:

Using a tool like curl (or any other HTTP client), you can test your API endpoints.

Example requests:

Retrieve all users:
curl http://localhost:5000/users

Response:

[

{"id": 1, "name": "John"},

{"id": 2, "name": "Jane"}

]

Retrieve a specific user:
curl http://localhost:5000/users/1

Response:

{"id": 1, "name": "John"}

That's it! You now have a basic REST API built using Python and Flask.

What's next?

From here, you can add more features to your API, such as user authentication, data validation, error handling, and so much more. Explore the world of Flask and REST APIs, and get creative with your own projects!

This guide was based on w3schools.com's tutorial on Building a RESTful API with Python and Flask.