/api/contacts

POST

Creates a new contact in your QMail address book.

Description

The `POST /api/contacts` endpoint allows you to add a new contact to your address book. The contact's email address must be unique and follow proper email format. If a contact with the same email address already exists, the request will fail with a 409 Conflict error.

Email Validation

The `auto_address` field must be a valid email address and is required. This ensures consistent formatting and prevents duplicate entries.

Duplicate Detection

If a contact with the provided email address already exists, the API will return a 409 Conflict error. Make sure to check for existing contacts before attempting to add new ones.

Request Body

Send a JSON object with the following properties:

Field Type Required Description
first_name string Required Contact's first name
auto_address string Required Contact's email address (must be valid email format)
last_name string Optional Contact's last name
middle_name string Optional Contact's middle name or initial
description string Optional Notes or description about the contact
sending_fee number Optional Custom sending fee for this contact
beacon_id string Optional Associated beacon identifier

Response

Returns a JSON object with the created contact information.

Success Response (201 Created)

status string
Status indicator - "created".
contact object
The newly created contact object with all fields including the generated user_id.

Example Success Response

{
  "status": "created",
  "contact": {
    "user_id": 123,
    "first_name": "Charlie",
    "last_name": "Brown",
    "middle_name": "M",
    "auto_address": "[email protected]",
    "description": "Team lead",
    "sending_fee": 2.0,
    "beacon_id": "beacon-xyz789"
  }
}

Example Error Response (409 Conflict)

{
  "error": "Contact already exists",
  "message": "A contact with email address '[email protected]' already exists"
}

Example Error Response (400 Bad Request)

{
  "error": "Validation error",
  "message": "Invalid email format for auto_address",
  "field": "auto_address"
}

Try it out

{}

Examples

JavaScript (fetch)

const API_HOST = 'http://localhost:8080';

async function addContact(contactData) {
    try {
        const response = await fetch(`${API_HOST}/api/contacts`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(contactData)
        });

        const result = await response.json();

        if (response.ok) {
            console.log('Contact created successfully!');
            console.log(`Contact ID: ${result.contact.user_id}`);
            console.log(`Name: ${result.contact.first_name} ${result.contact.last_name}`);
            console.log(`Email: ${result.contact.auto_address}`);
        } else if (response.status === 409) {
            console.error('Error: Contact already exists');
        } else {
            console.error('Error:', result.message || result.error);
        }
    } catch (error) {
        console.error('Request failed:', error);
    }
}

// Example usage
addContact({
    first_name: 'Charlie',
    last_name: 'Brown',
    middle_name: 'M',
    auto_address: '[email protected]',
    description: 'Team lead',
    sending_fee: 2.0,
    beacon_id: 'beacon-xyz789'
});

cURL

# Add a new contact
curl -X POST "http://localhost:8080/api/contacts" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Charlie",
    "last_name": "Brown",
    "middle_name": "M",
    "auto_address": "[email protected]",
    "description": "Team lead",
    "sending_fee": 2.0,
    "beacon_id": "beacon-xyz789"
  }'

# Minimal required fields
curl -X POST "http://localhost:8080/api/contacts" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Jane",
    "auto_address": "[email protected]"
  }'

Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

const ApiHost = "http://localhost:8080"

type ContactInput struct {
    FirstName   string  `json:"first_name"`
    LastName    string  `json:"last_name,omitempty"`
    MiddleName  string  `json:"middle_name,omitempty"`
    AutoAddress string  `json:"auto_address"`
    Description string  `json:"description,omitempty"`
    SendingFee  float64 `json:"sending_fee,omitempty"`
    BeaconID    string  `json:"beacon_id,omitempty"`
}

type Contact struct {
    UserID      int     `json:"user_id"`
    FirstName   string  `json:"first_name"`
    LastName    string  `json:"last_name"`
    MiddleName  string  `json:"middle_name"`
    AutoAddress string  `json:"auto_address"`
    Description string  `json:"description"`
    SendingFee  float64 `json:"sending_fee"`
    BeaconID    string  `json:"beacon_id"`
}

type CreateResponse struct {
    Status  string  `json:"status"`
    Contact Contact `json:"contact"`
}

type ErrorResponse struct {
    Error   string `json:"error"`
    Message string `json:"message"`
}

func main() {
    newContact := ContactInput{
        FirstName:   "Charlie",
        LastName:    "Brown",
        MiddleName:  "M",
        AutoAddress: "[email protected]",
        Description: "Team lead",
        SendingFee:  2.0,
        BeaconID:    "beacon-xyz789",
    }

    jsonData, _ := json.Marshal(newContact)

    resp, err := http.Post(
        fmt.Sprintf("%s/api/contacts", ApiHost),
        "application/json",
        bytes.NewBuffer(jsonData),
    )
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)

    if resp.StatusCode == http.StatusCreated {
        var result CreateResponse
        json.Unmarshal(body, &result)
        fmt.Println("Contact created successfully!")
        fmt.Printf("Contact ID: %d\n", result.Contact.UserID)
        fmt.Printf("Name: %s %s\n", result.Contact.FirstName, result.Contact.LastName)
        fmt.Printf("Email: %s\n", result.Contact.AutoAddress)
    } else {
        var errResult ErrorResponse
        json.Unmarshal(body, &errResult)
        fmt.Printf("Error: %s\n", errResult.Message)
    }
}

Related Endpoints

/api/contacts (GET)

List all contacts with pagination and search.

/api/contacts/{id} (DELETE)

Remove a contact from your address book.

/api/data/contacts/popular

Get your most frequently contacted addresses.