create a contact rest api using flask in python

To create a basic contact REST API using Flask in Python, we need to perform the following steps:

  1. Import Flask and jsonify modules
  2. Create an instance of the Flask class
  3. Define routes for the API endpoints
  4. Create a list to store the contact details
  5. Implement the CRUD operations for the contact list
  6. Run the Flask application

Here is a sample code demonstrating the above steps:

main.py
from flask import Flask, jsonify, request

app = Flask(__name__)

# Create a list to store the contacts
contacts = []

# Define the routes for the API endpoints
@app.route('/contacts', methods=['GET'])
def get_contacts():
    return jsonify({'contacts': contacts})

@app.route('/contacts/<int:id>', methods=['GET'])
def get_contact(id):
    contact = [contact for contact in contacts if contact['id'] == id]
    if len(contact) == 0:
        abort(404)
    return jsonify({'contact': contact[0]})

@app.route('/contacts', methods=['POST'])
def create_contact():
    if not request.json or not 'name' in request.json:
        abort(400)
    contact = {
        'id': len(contacts) + 1,
        'name': request.json['name'],
        'email': request.json.get('email', "")
    }
    contacts.append(contact)
    return jsonify({'contact': contact}), 201

@app.route('/contacts/<int:id>', methods=['PUT'])
def update_contact(id):
    contact = [contact for contact in contacts if contact['id'] == id]
    if len(contact) == 0:
        abort(404)
    if not request.json:
        abort(400)
    contact[0]['name'] = request.json.get('name', contact[0]['name'])
    contact[0]['email'] = request.json.get('email', contact[0]['email'])
    return jsonify({'contact': contact[0]})

@app.route('/contacts/<int:id>', methods=['DELETE'])
def delete_contact(id):
    contact = [contact for contact in contacts if contact['id'] == id]
    if len(contact) == 0:
        abort(404)
    contacts.remove(contact[0])
    return jsonify({'result': True})

# Run the application
if __name__ == '__main__':
    app.run(debug=True)
1610 chars
54 lines

You can test the API endpoints using a tool like Postman or cURL. Here are some example requests and responses:

  • GET /contacts
    • Returns a list of all contacts
    • Response: {'contacts': [{...}, {...}, ...]}
  • GET /contacts/1
    • Returns the contact with ID 1
    • Response: {'contact': {...}}
  • POST /contacts
    • Creates a new contact
    • Request: {'name': 'John', 'email': 'john@example.com'}
    • Response: {'contact': {...}}
  • PUT /contacts/1
    • Updates the contact with ID 1
    • Request: {'name': 'John Doe', 'email': 'johndoe@example.com'}
    • Response: {'contact': {...}}
  • DELETE /contacts/1
    • Deletes the contact with ID 1
    • Response: {'result': True}

gistlibby LogSnag