Get started with GeoServer and its REST API

An open source data management system with a full API and built-in WMS and WFS server

GeoServer is an open source server for managing geographic information system (GIS) data sources and serving them easily through Web Feature Service (WFS) and Web Map Service (WMS) web services. It includes a comprehensive Representational State Transfer (REST) API for managing data at run time from complex web applications without manual intervention, and it works well in tandem with the OpenLayers mapping tool. This article introduces and explores GeoServer, including the benefits of creating a PHP wrapper class for the API.

Share:

Christopher Michaelis, Developer, Consultant

Christopher Michaelis photoChristopher Michaelis is a software developer who specializes in web applications, educational tools, and spatial programming. He attended Utah State University and Idaho State University, studying computer science and geographic information science. His experience covers a wide range of development areas, including applications for environmental modeling, education, diabetes data analysis, system-administration tools, web hosting, location-based services, web mapping, and cross-platform application development.



30 April 2013

Also available in Russian Japanese

If you serve geospatial data to the web, you're probably familiar with MapServer, the usual first choice. Although MapServer is excellent at serving static data sources, configuring it is a time-consuming manual process. No API-based configuration or data management solutions for it are readily available. If you're looking for a complete solution to long-term data management or a complete basis for a GIS-oriented web application, GeoServer might be a better choice for you.

GeoServer is an open source server that makes management of GIS data easy. Like MapServer, it provides data using the WMS and WFS standards. It also supports WFS-T, used to modify actual data, plus Geography Markup Language (GML), Keyhole Markup Language (KML), and many other formats. Data is organized internally into workspaces and data stores and can use disk-based storage or PostGIS. With the included REST API, you can manage data sets in real time. The software also includes a complete web interface.

In an in-depth introduction to GeoServer, explore the installation process, the web-based administration GUI, and how to use the REST API through a PHP wrapper class to simplify operations.

Prerequisite knowledge and where to find it

Before you start, you want a basic understanding of what GIS is all about and passing familiarity with GIS terms such as shapefile, vector feature attributes, and projections. See Resources for a link to the GIS Lounge's GIS 101 page for a great tutorial on these basics.

WMS is an interface for requesting map imagery and WFS is an interface for requesting map vector data. WMS is more appropriate if your goal is solely data display. WFS is more appropriate if you need your users to interact with the underlying data (for example, query its attribute table values or modify the data). Modification of WFS features is often called WFS-T or transactional WFS.

Many of the operations you do with GeoServer are specified in XML format, so familiarity with XML in general is useful. See Resources for a link to an "XML Basics" tutorial that provides an excellent overview of XML.

To follow along with this article's installation procedures, you need basic familiarity with the Linux® command line and access to a Linux server. Knowledge of PostgreSQL and PostGIS (and access to a PostGIS server) can be useful if you want to use PostGIS as your data storage system, rather than on-disk shapefiles.

Lastly, OpenLayers is an excellent JavaScript client-side mapping tool that can work closely with GeoServer to create spatially enabled web applications. For information about OpenLayers, see "Bring data together with OpenLayers."


Installation

GeoServer is a Java™ servlet. As such, it runs inside of a servlet container, such as Apache Tomcat. You can also run it as a stand-alone servlet through the built-in Jetty servlet container, which is good for local testing. Tomcat is better for large or high-volume installations, so this article covers only that option.

Server requirements

Any Linux server that you have root access to is sufficient. GeoServer can easily run in a small VM instance, such as a small IBM PowerVM® instance or System Z® partition. Your needs scale directly with the amount of traffic you plan to send to the GeoServer installation. Allow enough disk space to store all of your GIS data, plus around 5 GB for the operating system and GeoServer. At least 512 MB of memory is recommended. Microsoft® Windows® and Mac OS® X are also supported, but Linux is best for production use. All instructions in this article assume that you use an Ubuntu or Debian server.

Installation of Apache Tomcat and the GeoServer WAR

Begin by installing Tomcat with apt-get install tomcat7. When installation is complete, look for a test page at http://your-server:8080. Next, visit the GeoServer Stable Downloads page (see Resources) and download the Web Archive (WAR) compressed file. Extract the ZIP and move the geoserver.war file from the archive to /var/lib/tomcat7/webapps/. Ignore the rest of the files from the compressed file. Restart Tomcat with service tomcat7 restart, and see your default GeoServer installation at http://your-server:8080/geoserver/. The Tomcat server starts automatically on restart.

The default data directory is /var/lib/tomcat6/webapps/geoserver/data/. This directory contains security configuration and is the data store default location. The location also contains a subdirectory named data, which is for actual GIS data store files, so you often have paths that include the data portion twice (for example, /var/lib/tomcat7/webapps/geoserver/data/data/USA/state.shp). If this set up bothers you, you can rename the data store location to something like gis_data to be more explicit.

If you want to run on a port other than 8080, edit the /etc/tomcat7/server.xml file. Look for the <Connector port="8080" protocol="HTTP/1.1" line and change 8080 to 80 (or another port that you want to use), save the file, and then restart Tomcat.

Optional extensions

Many optional extensions for GeoServer are available that provide more data sources (such as IBM DB2®) and new features (such as Web Processing Service [WPS], Excel output). These extensions are available from the GeoServer download page (see Resources).

To install any extension, extract it to /var/lib/tomcat7/webapps/geoserver/WEB-INF/lib/. After you install an extension (install all the extensions that you want in the same step), restart GeoServer (sudo service tomcat7 restart).

Two useful extensions are OGR and MySQL. OGR supports more vector-data output options and MySQL supports MySQL data storage. When you install the OGR extension, make sure that you have a working ogr2ogr binary on your system. If you do not, install the gdal-bin package with sudo apt-get install gdal-bin. After you restart GeoServer, the layer preview drop-down list displays the OGR format options. Similarly, after you install MySQL and restart the system, MySQL databases are listed as a storage option under New data source. MySQL is an unsupported extension, so unless you must use MySQL, PostGIS (PostgreSQL) is a better option.


Web GUI

After installation, visit the administrative GUI to complete the basic setup steps that are outlined here, even if you plan to use GeoServer entirely from your web application.

Initial configuration

The default user name is admin, with geoserver as the password. After you log in, click Security->Users in the left menu. In the list that displays, click the admin user name, and you can change the administrative password. You can also use this tool to add new users.

You might upload any shapefile data sources that you have or prepare your PostGIS databases. For example, for a US data set, create the /var/lib/tomcat7/webapps/geoserver/data/data/USA directory. Upload your data files. Change ownership of the files to whoever runs your GeoServer instance (tomcat7 if you use Apache Tomcat). If you use PostGIS, you can use the shp2pgsql utility to import shapefiles. For more information about loading data into PostGIS, see Resources.

GeoServer organizes data (layers) within workspaces and data stores. A layer is an individual data set, such as roads or lakes. A workspace provides a logical grouping of data for a particular project or geographic region. A workspace can contain one or more data stores, which identify the physical storage location of the data (for example, a directory or file on disk or a PostGIS database table).

After you prepare your data, click the appropriate options on the Data menu to add them to GeoServer. You can leave the default for most options. For workspaces, the namespace must be a unique value, set up as http://yourservername/workspacename. Adding layers is called publishing layers. In this process, choose the correct coordinate system — spatial reference system (SRS) — and to click Compute under each of the two bounding boxes. Repeat this process for all of your initial workspaces, data stores, and layers.

If you use PostGIS, add at least one shape to each database table before you add it to GeoServer for the best results. After you configure your layers, preview them directly from GeoServer, as in Figure 1:

Figure 1. Layer preview
Screen capture showing the Layer Preview function, including attribute data for one of the shapes

Security

With GeoServer, you can set up user roles that control access to specific workspaces and services. If your GeoServer installation is publicly accessible, experiment under the Security menu to make sure that you understand how roles work. In many cases, you might place the installation behind a firewall or on a private network and use a single login with full access. Then, you can do all operations on the GeoServer through your own software and the PHP proxy, which I cover in the next section.

Ongoing maintenance and data management

Ensure that your server disk space, processor, and memory continue to meet growing demands over time. Schedule regular backups of your server. (Back up the entire /var/lib/tomcat7/webapps/geoserver directory and any PostGIS databases.) To avoid confusion when you have several hundred layers, plan a naming convention for workspaces, namespaces, data stores, and file names well in advance.


The REST API and a PHP wrapper

GeoServer includes an API that can take most actions programmatically. This API makes GeoServer useful as a data management tool and as a cornerstone for a complex web application that automatically adds and removes layers as needed. You can use the GeoServer API directly, but it's useful to construct a PHP wrapper class that simplifies operations and encapsulates needed communications. See Download to get a simple API wrapper, along with a test page, that you can use and extend for your own purposes.

You run all API operations with a GET, POST, PUT, or DELETE operation to the base URL, which is http://yourserver:8080/geoserver/rest/. Add the object of interest to you (for example, workspaces) to that base URL, optionally followed by a period and the return format that you prefer — usually XML, JavaScript Object Notation (JSON), or HTML. Thus, a GET operation to http://yourserver:8080/geoserver/rest/workspaces.xml lists all workspaces in XML format. The GET statement generally returns the results in the same format you use when you create an instance of an object through a POST statement or update it through PUT. You seldom have to provide all of the details that the GET operation returns. The PHP wrapper class (see Download) includes examples of specific REST API actions. For a link to the REST Configuration API Reference, see Resources.

Listing, creating, and deleting data

The sample PHP wrapper includes simple functions to list, delete, and create each of the major object types. When you create a PostGIS data store, the database must exist. When you use createLayer for a PostGIS table, the layer name is the table name. Make sure that the table contains at least one shape before you add the layer to GeoServer. When you use a Shapefile Directory data store, the layer name is the file name (without path), and the file must exist in the data store location. Listing 1 illustrates the process of creating a workspace, data store, and layer in one quick operation:

Listing 1. Creating a workspace and PostGIS data store and publishing a layer
include "GeoserverWrapper.php";
$geoserver = new GeoserverWrapper('http://geosrvr.chrismichaelis.com/geoserver',
          $username, $password);

// public function createWorkspace($workspaceName)
$geoserver->createWorkspace('delineation_34');

// public function createPostGISDataStore($datastoreName, $workspaceName,
//        $databaseName, $databaseUser, $databasePass, $databaseHost = 'localhost',
//        $databasePort = '5432')
$geoserver->createPostGISDataStore('d34_outputs', 'delineation_34', 'delineations',
          'gisuser', 'gisuser', 'localhost');

// Create table
pg_query("CREATE TABLE d34_stream_output (...)"); 
// Add shape(s) according to your own program logic
pg_query("INSERT INTO d34_stream_output (...)");

// public function createLayer($layerName, $workspaceName, $datastoreName,
//        $description = '')
$geoserver->createLayer('d34_stream_output', 'delineation_34', 'd34_outputs',
          'Delineation outputs for run #34');

Viewing layers

With the viewLayer function, you can request a data set in GML or in KML (which is the Google Earth format). If you want to use KML output directly in Google Earth, make sure that your data set is stored in latitude and longitude coordinates. Use the viewLayerLegend function to retrieve a legend image square for building your own legend layouts.

The easiest and most flexible way to display GeoServer data is with OpenLayers. Because OpenLayers is a browser-based tool, all requests from your web page must have the same domain name and port. This restriction is a security feature that also prevents you from communicating directly with a GeoServer installation on a port or server other than the main website. Thus, the PHP wrapper also provides a wfsPost function, which passes requests along to GeoServer. The sample tester.php API test class uses this function to capture and redirect requests from OpenLayers to GeoServer. Listing 2 shows the relevant code:

Listing 2. Capturing and redirecting GeoServer requests
// See if we're passing a WFS request to the server on private net
// (or for cross domain protection bypassing proxy)
$pathParts = explode('/', $_SERVER['PATH_INFO']);
if ($pathParts[1] == 'wfsauth') {
  $unused = array_shift($pathParts);
  $unused = array_shift($pathParts);
  $user = array_shift($pathParts);
  $pass = array_shift($pathParts);

  // Pass through for WFS using username and password to follow
  include "GeoserverWrapper.php";
  $geoserver = new GeoserverWrapper('http://geosrvr.chrismichaelis.com/geoserver',
          $user, $pass);
  $wfs = implode('/', $pathParts);
  if ($_SERVER['QUERY_STRING'] != '') $wfs .= '?' . $_SERVER['QUERY_STRING'];
  // public function wfsPost($apiPath, $post)
  echo $geoserver->wfsPost($wfs, file_get_contents('php://input'));
  return;
} else if ($pathParts[1] == 'wfs') {
  $unused = array_shift($pathParts);
  $unused = array_shift($pathParts);

  // No auth required
  include "GeoserverWrapper.php";
  $geoserver = new GeoserverWrapper('http://geosrvr.chrismichaelis.com/geoserver');
  $wfs = implode('/', $pathParts);
  if ($_SERVER['QUERY_STRING'] != '') $wfs .= '?' . $_SERVER['QUERY_STRING'];
  echo $geoserver->wfsPost($wfs, file_get_contents('php://input'));
  return;
}

Listing 3 shows how to connect OpenLayers to a WFS layer through this PHP proxy. Although the code and function name say wfs, the same approach works equally well if you prefer a WMS layer. WMS provides map imagery in Portable Network Graphics (PNG) format. WFS provides actual map data in GML format that is rendered on the client side by JavaScript.

Listing 3. Using the GeoServer WFS layer from OpenLayers
wfs = new OpenLayers.Layer.Vector("Editable Features", {
  strategies: [ new OpenLayers.Strategy.BBOX(), new OpenLayers.Strategy.Save() ],
      /* The preceding line enables WFS-T. */
  projection: new OpenLayers.Projection("EPSG:900913"),
      /* 900913 = Google projection, which is required to use Google Earth base layers */
  protocol: new OpenLayers.Protocol.WFS({
    version: "1.1.0",
    srsName: "EPSG:900913",
    url: "http://.../geoserver_api/index.php/wfsauth/USERNAME/PASSWORD",
    featureNS :  "http://chrismichaelis.com/test_1",
    featurePrefix: 'test_1',
    featureType: "roads2",
    geometryName: 'the_geom',
    schema: "http://.../geoserver_api/index.php/wfsauth/USERNAME/PASSWORD/" +
      "DescribeFeatureType?version=1.1.0&typename=test_1:roads2"
  })
});

map.addLayer(wfs);

You can also use this approach to implement some additional security. Suppose GeoServer is on a private network or behind a firewall. When you interact with it through your PHP application, check the request URL in detail to see which users of your web application have access to the requested layer.

Using WFS-T to modify data

One advantage of WFS over WMS is that you can do transactions to update the data set on the server directly. If you use OpenLayers, include the line in Listing 3 that creates a Save strategy. Use the OpenLayers DeleteFeature, DrawFeature, and ModifyFeature controls for quick, easy shape editing capabilities in your web application.

You might want to do edit operations directly from your own PHP code rather than try to edit the on-disk shapefile or PostGIS table directly. The API wrapper provides the executeWFSTransaction function, which accepts XML transaction statements. The namespace and layer are specified as part of the transaction. For more information about writing WFS-T transaction statements, see the GEOSS Transactional WFS tutorial item in Resources.

Listing 4 illustrates running a simple WFS-T transaction that inserts an L-shaped line:

Listing 4. Running a WFS-T transaction to insert a small shape
$WFSTRequest = '
<?xml version="1.0" ?>
<wfs:Transaction service="WFS" version="1.1.0" xmlns:wfs="http://www.opengis.net/wfs"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.opengis.net/wfs
          http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">
  <wfs:Insert>
    <feature:roads2 xmlns:feature="http://chrismichaelis.com/test_1">
      <feature:the_geom>
        <gml:MultiCurve srsName="EPSG:900913" xmlns:gml="http://www.opengis.net/gml">
          <gml:curveMember>
            <gml:LineString>
              <gml:posList>
                -11575958.058425 5537202.2479459 -11575346.562199
                5524666.5753089 -11561893.645222 5524666.5753089
              </gml:posList>
            </gml:LineString>
          </gml:curveMember>
        </gml:MultiCurve>
      </feature:the_geom>
    </feature:roads2>
  </wfs:Insert>
</wfs:Transaction>
';

$geoserver->executeWFSTransaction($WFSTRequest);

In Listing 4, notice that coordinate projection matches what's stated in the srsName XML attribute.

Creating and assigning styles

WFS layers are typically styled on the client side by using OpenLayers in JavaScript. WMS layers, which are images that are generated on the server, rely on style definitions to know how to render them. You define these styles with Styled Layer Descriptor (SLD) notation. SLD is an XML-based format for setting up coloring based on many options, such as different attribute ranges and values. GeoServer stores these styles with a name, so you can save one style and reuse it in the future. SLD is best learned by example. For many ready-to-use samples, see the SLD Cookbook item in Resources.

The API wrapper provides functions to list, create, and delete styles, plus assign a style to a layer. A single layer can have multiple styles. When you have multiple styles, your WMS request can specify the style to use, as in the OpenLayers WMS example in Listing 5:

Listing 5. Requesting a specific style from a WMS layer with OpenLayers
map.addLayer(
  new OpenLayers.Layer.WMS(
    // You can again use the "PHP Proxy" here if needed.
    "test_workspace:roads2", "http://geosrvr.chrismichaelis.com/geoserver/roads2/wms",
    {
      LAYERS: 'test_workspace:roads2',
      STYLES: 'simple_roads'.
      tiled: true
    },
    {
      buffer: 0,
      displayOutsideMaxExtent: true,
      isBaseLayer: true,
      yx : {'EPSG:4326' : true}
    } 
  )
);

Conclusion

Integrating GeoServer into your web applications is a great way to reduce the need for mundane data management code and gain a comprehensive WMS and WFS-T server at the same time. You are free to use the examples and approach that is outlined here for your own needs.


Download

DescriptionNameSize
Geoserver PHP API wrapper and testerGeoserverWrapperAPIandTester.zip6KB

Resources

Learn

Get products and technologies

  • GeoServer Stable Downloads: Download GeoServer and optional extensions.
  • Apache Tomcat: Try the Tomcat servlet container for a great way to run GeoServer.
  • Evaluate IBM products in the way that suits you best: Download a product trial, try a product online, use a product in a cloud environment, or spend a few hours in the SOA Sandbox learning how to implement Service Oriented Architecture efficiently.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Web development
ArticleID=870977
ArticleTitle=Get started with GeoServer and its REST API
publish-date=04302013