How to Manage Real Estate Agencies via WPResidence API

wpresidence-api

Managing real estate agencies efficiently requires robust tools for automation and integration with various systems. The WPResidence API provides a comprehensive set of endpoints for agency management, enabling developers to create, read, update, and delete agency data programmatically. This article explores leveraging these API endpoints to streamline agency management in real estate platforms.

What is an Agency in WPResidence?

In WPResidence, an agency is a business entity that represents a real estate company. Agencies are stored as custom post types (estate_agency) in WordPress with associated metadata. Each agency can have:

  • Basic information (name, description, contact details)
  • Media (logo, featured images)
  • Social profiles
  • Custom fields
  • Associated agents
  • Property listings

Agencies serve as organizational units that group agents and properties, providing a hierarchical structure to your real estate platform. They can be assigned to specific geographical areas, property types, or market segments.

Retrieving a List of Agencies via API

The WPResidence API provides a flexible endpoint for retrieving agencies with robust filtering capabilities.

Endpoint: POST /wpresidence/v1/agencies

This endpoint uses POST method to accept a JSON body with filtering parameters.

Request Parameters

{
  "page": 1,
  "posts_per_page": 10,
  "fields": "ID,title,description,agency_email,agency_phone,agency_address",
  "meta": {
    "agency_city": {
      "value": "New York",
      "compare": "=",
      "type": "CHAR"
    },
    "agency_size": {
      "value": 10,
      "compare": ">",
      "type": "NUMERIC"
    }
  },
  "taxonomies": {
    "property_category": [24, 25],
    "property_action_category": [12]
  }
}

Key parameters include:

  • page: Current page number for pagination (default: 1)
  • posts_per_page: Number of agencies per page (default: 10)
  • fields: Comma-separated list of fields to include in the response
  • meta: Object containing metadata filters
    • key: Metadata field name
    • value: Value to compare against
    • compare: Comparison operator (=, !=, >, >=, <, <=, LIKE, NOT LIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, EXISTS, NOT EXISTS)
    • type: Data type (NUMERIC, BINARY, CHAR, DATE, DATETIME, DECIMAL, SIGNED, TIME, UNSIGNED)
  • taxonomies: Object with taxonomy names as keys and arrays of term IDs as values

Response Structure

{
  "status": "success",
  "query_args": {
    "post_type": "estate_agency",
    "paged": 1,
    "posts_per_page": 10,
    "meta_query": [...],
    "tax_query": [...]
  },
  "data": [
    {
      "ID": 123,
      "title": "Skyline Properties",
      "description": "Premier real estate agency serving the New York area",
      "agency_email": "contact@skylineproperties.com",
      "agency_phone": "212-555-1234",
      "agency_address": "123 Madison Ave, New York, NY 10016"
    },
    // Additional agencies...
  ],
  "total": 45,
  "pages": 5
}

Best Practices for Agency Listing

  1. Efficient Field Selection: Only request fields you need to reduce payload size
  2. Pagination: Always implement pagination for better performance
  3. Consistent Sorting: Sort by relevant criteria for better user experience
  4. Error Handling: Implement proper error handling for edge cases
  5. Caching: Cache responses when appropriate to reduce API calls

Fetching Details for a Single Agency

To retrieve detailed information about a specific agency, use the single agency endpoint.

Endpoint: GET /wpresidence/v1/agency/{id}

Where {id} is the agency’s post ID.

Request Parameters

  • id: (Required) The agency ID (path parameter)
  • fields: (Optional) Comma-separated list of fields to include in the response

Example request:

GET /wpresidence/v1/agency/123?fields=ID,title,description,agency_email,agency_phone,agency_address,agency_mobile

Response Structure

The response provides detailed information about the requested agency with all the metadata fields flattened into the top level of the response object:

{
  "ID": 123,
  "title": "Skyline Properties",
  "description": "Premier real estate agency serving the New York area",
  "agency_email": "contact@skylineproperties.com",
  "agency_phone": "212-555-1234",
  "agency_mobile": "917-555-6789",
  "agency_address": "123 Madison Ave, New York, NY 10016",
  "agency_website": "https://skylineproperties.com",
  "agency_license": "RE-12345-NY",
  "agency_tax_number": "123456789",
  "agency_opening_hours": "Mon-Fri: 9am-6pm, Sat: 10am-4pm",
  "agency_city": "New York",
  "agency_state": "NY",
  "agency_zip": "10016",
  "agency_country": "USA",
  "agency_facebook": "skylinepropertiesny",
  "agency_twitter": "skylineprop_ny",
  "agency_linkedin": "skyline-properties-ny",
  "agency_instagram": "skylineproperties_ny",
  "agency_pinterest": "skylinepropertiesny",
  "featured_image": "https://example.com/wp-content/uploads/2023/01/skyline-properties-logo.jpg",
  "agent_count": 12
}

Creating a New Agency (Step-by-Step with API Request)

New agencies can be created using the agency creation endpoint.

Endpoint: POST /wpresidence/v1/agency/add

Authentication and Permissions

The endpoint verifies:

  1. JWT token validity
  2. User login status
  3. User permission to create agencies

Required Fields

At minimum, these fields are required:

  • agency_name: Agency’s name
  • agency_email: Valid email address

Step-by-Step API Request

  1. Prepare the authentication token
    • Obtain a valid JWT token through the authentication endpoint
    • Include the token in the Authorization header
  2. Construct the request payload
{
  "agency_name": "Horizon Realty Group",
  "agency_email": "info@horizonrealty.com",
  "agency_description": "Horizon Realty Group specializes in luxury properties in coastal areas with over 25 years of market experience.",
  "agency_phone": "305-555-7890",
  "agency_mobile": "305-555-7891",
  "agency_address": "789 Ocean Drive, Miami Beach, FL 33139",
  "agency_website": "https://horizonrealtygroup.com",
  "agency_license": "FL-REB-78901",
  "agency_tax_number": "87-6543210",
  "agency_opening_hours": "Mon-Sat: 9am-7pm, Sun: 11am-4pm",
  "agency_city": "Miami Beach",
  "agency_state": "FL",
  "agency_zip": "33139",
  "agency_country": "USA",
  "agency_facebook": "horizonrealtygroup",
  "agency_twitter": "horizonrealty",
  "agency_linkedin": "horizon-realty-group",
  "agency_instagram": "horizonrealtygroup",
  "agency_custom_data": [
    {"label": "Year Founded", "value": "1998"},
    {"label": "Specialization", "value": "Luxury Coastal Properties"},
    {"label": "Areas Served", "value": "Miami-Dade County, Broward County"}
  ],
  "featured_image": "https://example.com/wp-content/uploads/horizon-realty-logo.jpg",
  "user_registration": {
    "username": "horizonrealty",
    "email": "admin@horizonrealty.com",
    "password": "secure_password_123",
    "role": "agency"
  }
}
  1. Send the request
POST /wpresidence/v1/agency/add
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json

{JSON payload from step 2}
  1. Process the response
{
  "status": "success",
  "agency_id": 456,
  "message": "Agency created successfully."
}

Additional Fields and Features

  • agency_custom_data: Array of custom fields with label-value pairs
  • featured_image: URL of an image to set as the agency’s logo or profile picture
  • user_registration: Creates a WordPress user associated with the agency

Editing an Existing Agency’s Information

Agency information can be updated through the agency update endpoint.

Endpoint: PUT /wpresidence/v1/agency/edit/{id}

Where {id} is the agency’s post ID.

Authentication and Permissions

The API verifies:

  1. JWT token validity
  2. User login status
  3. Agency existence and correct post type
  4. User is either the agency creator or has admin permissions

Request Payload Example

{
  "agency_name": "Horizon Realty Group International",
  "agency_description": "Updated description with additional services and market areas.",
  "agency_phone": "305-555-8888",
  "agency_opening_hours": "Mon-Sat: 8am-8pm, Sun: 10am-5pm",
  "agency_custom_data": [
    {"label": "Year Founded", "value": "1998"},
    {"label": "Specialization", "value": "Luxury Coastal and International Properties"},
    {"label": "Areas Served", "value": "Miami-Dade County, Broward County, International"}
  ],
  "featured_image": "https://example.com/wp-content/uploads/horizon-realty-new-logo.jpg"
}

Only include fields that need to be updated; omitted fields remain unchanged.

Response

{
  "status": "success",
  "agency_id": 456,
  "message": "Agency updated successfully."
}

Deleting an Agency: What Happens to Associated Agents?

Agencies can be permanently removed using the agency deletion endpoint.

Endpoint: DELETE /wpresidence/v1/agency/delete/{id}

Where {id} is the agency’s post ID.

Authentication and Permissions

The API checks:

  1. JWT token validity
  2. User login status
  3. Agency existence and correct post type
  4. User is either the agency creator or has admin permissions

Impact on Associated Entities

When an agency is deleted, the system performs several cleanup operations:

  1. Agency Post: The agency post and all its metadata are permanently removed
  2. User Association: If there’s a WordPress user linked to the agency, the user_agency_id meta is cleared
  3. Agents: Agents associated with the agency remain in the system but lose their agency association
  4. Properties: Properties listed under the agency remain but may need reassignment

Best Practices for Agency Deletion

  1. Pre-deletion Audit: Before deletion, audit all associated entities
  2. Agent Reassignment: Reassign agents to other agencies if necessary
  3. Property Reassignment: Ensure properties are reassigned to appropriate agents or agencies
  4. Backup: Create a backup of agency data before deletion
  5. Communication: Notify relevant stakeholders about the agency removal

Linking Agencies with Agents & Properties

The WPResidence system allows for connecting agencies, agents, and properties to create a hierarchical structure.

Agency-Agent Relationship

Agents can be associated with agencies through:

  1. User Meta: A user’s user_agency_id meta field contains the agency post ID
  2. Agent Meta: An agent post has agency-related metadata
  3. Agency List: Agencies maintain a list of associated agents

When updating an agent’s information, you can change their agency association:

{
  "agency_id": 456,
  "other_agent_fields": "..."
}

Agency-Property Relationship

Properties can be associated with agencies directly or through agents:

  1. Direct Association: A property can have an agency_id field
  2. Via Agent: A property associated with an agent inherits the agent’s agency

Syncing Agency Data with User Accounts

When an agency record is updated, the API can sync the changes to the associated WordPress user:

  1. The system identifies the user linked to the agency
  2. Updates relevant user meta fields to match agency data
  3. Maintains consistency between the agency post and user account

API Security & Role-Based Access

The WPResidence API implements several security measures to protect agency data:

Authentication Mechanisms

  1. JWT Token: All agency management endpoints require a valid JWT token
  2. User Validation: The system verifies the user exists and is logged in
  3. Token Expiration: JWT tokens have expiration times for security

Permission Checks

Different operations require different permission levels:

  1. Viewing Agencies: Public access (no special permissions needed)
  2. Creating Agencies: Requires publish_estate_agencies capability
  3. Updating Agencies: Requires being the agency author or having edit_others_posts capability
  4. Deleting Agencies: Requires being the agency author or having edit_others_posts capability

Role-Based Access Control

The API validates user roles against required capabilities:

// Example permission check (simplified)
if (intval($agency->post_author) !== intval($user_id) && !current_user_can('edit_others_posts')) {
    return new WP_Error(
        'rest_forbidden',
        __('You do not have permission to update this agency.'),
        ['status' => 403]
    );
}

Security Best Practices

  1. Secure Token Storage: Store JWT tokens securely and never expose them
  2. HTTPS: Always use HTTPS for API communications
  3. Minimal Permissions: Assign users the minimum necessary permissions
  4. Input Validation: Validate all input data before processing
  5. Rate Limiting: Implement rate limiting to prevent abuse
  6. Audit Logging: Log all critical operations for security auditing
  7. Error Handling: Implement proper error handling without exposing sensitive information

Conclusion

The WPResidence API provides a comprehensive set of tools for managing real estate agencies programmatically. By leveraging these endpoints, developers can create integrated systems that automate agency management tasks, maintain data consistency across platforms, and provide robust administrative interfaces.

Key takeaways for successful agency management via API:

  1. Understand the authentication and permission requirements
  2. Follow the required field formats and data structures
  3. Handle agency relationships carefully, especially when updating or deleting
  4. Implement proper security measures and role-based access control
  5. Use field filtering to optimize response payloads
  6. Consider the impact of operations on associated entities

With these practices in place, the WPResidence API can significantly enhance productivity and data integrity in real estate agency management systems.

Official documentation is here : https://www.postman.com/universal-eclipse-339362/wpresidence/overview

Read next

Caching Strategies for Real Estate Websites

Caching Strategies for Real Estate Websites

Real estate websites have a speed problem. You’re dealing with high-resolution photos, interactive maps, virtual tours, and search filters that need to work fast. When traffic spikes during an open