Skip to content

API Configuration

Göktürk edited this page Feb 5, 2025 · 2 revisions

API & Backend Configuration

This project integrates with GeoServer for spatial data management and a Django backend for participation-related operations. The API integration is handled through Pinia stores, ensuring state management is synchronized with the API responses.

Important Note on Function Documentation

Each function in the project is documented using TSDoc comments within its respective file. For detailed explanations of function parameters, return values, and usage, please refer directly to the corresponding source files in the project.

For example:

  • API functions → Check store/geoserver.ts and store/participation.ts.
  • Filtering functions → See components/Map/Layer/Filter/AttributeFiltering.vue and GeometryFiltering.vue.
  • State management functions → Refer to store/map.ts, store/filter.ts, etc.

For a complete breakdown of how each function works, refer to its respective TypeScript file and its TSDoc comments.

Technology Stack

  • GeoServer – Provides vector and raster layers via OGC-compliant APIs.
  • Django Backend – Manages participation data and user submissions.
  • Pinia – Manages API requests and application state.

GeoServer API Integration

GeoServer API is accessed through the store/geoserver.ts store module, which handles:

  • Fetching available layers and workspaces.
  • Retrieving vector layer details and GeoJSON sources.
  • Managing layer styles and metadata.

Key Functions in geoserver.ts

1. Fetching Available Layers

Retrieves a list of layers from GeoServer.

  async function getLayerList(
    workspaceName?: string
  ): Promise<GeoserverLayerListResponse> {
    let url = new URL(`${import.meta.env.VITE_GEOSERVER_REST_URL}/layers`);
    /* eslint-disable */
    if (workspaceName) {
      url = new URL(
        `${
          import.meta.env.VITE_GEOSERVER_REST_URL
        }/workspaces/${workspaceName}/layers`
      );
    }
    const response = await fetch(url, {
      method: "GET",
      redirect: "follow",
      headers: new Headers({
        "Content-Type": "application/json",
        Authorization: `Basic ${auth}`,
      }),
    });
    return await response.json();
  }

2. Retrieving Workspace List

Fetches available workspaces from GeoServer.

  async function getWorkspaceList(): Promise<WorkspaceListResponse> {
    const url = new URL(
      `${import.meta.env.VITE_GEOSERVER_REST_URL}/workspaces`
    );
    const response = await fetch(url, {
      method: "GET",
      redirect: "follow",
      headers: new Headers({
        "Content-Type": "application/json",
        Authorization: `Basic ${auth}`,
      }),
    });
    return await response.json();
  }

3. Fetching Layer Details

Retrieves metadata for a specific layer.

  async function getLayerDetail(url: string): Promise<GeoServerVectorTypeLayerDetail|GeoserverRasterTypeLayerDetail> {
    const response = await fetch(url, {
      method: "GET",
      redirect: "follow",
      headers: new Headers({
        "Content-Type": "application/json",
        Authorization: `Basic ${auth}`,
      }),
    });
    return await response.json();
  }

4. Fetching GeoJSON Layer Source

Gets GeoJSON data for a vector layer.

  async function getGeoJSONLayerSource(layer: string, workspace: string, bbox?:string, cqlFilter?:string): Promise<any> {
    const url = new URL(
      `${import.meta.env.VITE_GEOSERVER_BASE_URL}/${workspace}/wms?service=WMS&version=1.1.0&request=GetMap&layers=${workspace}:${layer}&bbox=${bbox ?? ""}&width=512&height=512&srs=EPSG:4326&format=geojson&CQL_FILTER=${cqlFilter ?? ""}&styles=`
    );
    console.log(url);
    const response = await fetch(url, {
      method: "GET",
      redirect: "follow",
      headers: new Headers({
        "Content-Type": "application/geojson",
        Authorization: `Basic ${auth}`,
      }),
    });
    return await response.json();
  }

5. Fetching Layer Styling Information

Retrieves style details for a given layer.

  async function getLayerStyling(url:string):Promise<any> {
    const response = await fetch(url,{
      method: "GET",
      redirect: "follow",
      headers: new Headers({
        "Content-Type": "application/vnd.geoserver.mbstyle+json",
        Authorization: `Basic ${auth}`,
      }),
    });
    if (!response.ok) {
      throw new Error("Failed to fetch layer styling.");
    }
    return response.json();
  }

Participation API Integration

Participation-related API calls are handled in store/participation.ts. This module communicates with a Django backend, managing campaigns and user submissions.

Key Functions in participation.ts

1. Fetching Active Campaigns

Retrieves all active participation campaigns.

async function getActiveCampaigns(): Promise<CampaignListItem[]> {
    const url = `${import.meta.env.VITE_GEONODE_REST_URL}/v2/cpt/campaigns`;
    try {
        const response = await fetch(url, {
            method: "GET"
        });
        return await response.json();
    } catch (error) {
        throw new Error(`Error fetching campaigns: ${String(error)}`);
    }
}

2. Fetching Campaign Details

Gets detailed information about a specific campaign.

async function getCampaignDetail(campaignURL: string): Promise<CampaignDetail> {
    const url = `${import.meta.env.VITE_GEONODE_REST_URL}/v2/cpt/campaigns/${campaignURL}`;
    try {
        const response = await fetch(url, {
            method: "GET"
        });
        return await response.json();
    } catch (error) {
        throw new Error(`Error fetching campaign detail: ${String(error)}`);
    }
}

3. Sending User Feedback

Submits feedback from users participating in a campaign.

async function sendFeedback(feed: PostRating|PostFeedback|PostFeedbackRating): Promise<void> {
    feedbackOnProgress.value = false;
    locationSelectionOnProgress.value = false;
    drawTool.externalAppOnProgress = false;
    const url = `${import.meta.env.VITE_GEONODE_REST_URL}/v2/cpt/feedback/`;
    const feedback = await fetch(url, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        },
        body: JSON.stringify(feed)
    });
    if (!feedback.ok) {
        throw new Error("Error sending feedback");
    }
}

Best Practices for API Integration

  • Use centralized state management – API responses are stored in Pinia for easy access across components.
  • Cache frequently accessed data – Prevent redundant API calls by storing results.
  • Handle errors gracefully – Implement proper error handling for API failures.
  • Use async/await for API requests – Ensures better readability and error management.

For further details, refer to the respective Pinia store modules (geoserver.ts and participation.ts).