{"id":9906,"date":"2025-09-05T16:15:23","date_gmt":"2025-09-05T19:15:23","guid":{"rendered":"https:\/\/www.fernandoquadro.com.br\/html\/?p=9906"},"modified":"2025-09-05T17:41:30","modified_gmt":"2025-09-05T20:41:30","slug":"importar-shapefile-para-postgis-via-api-rest-do-geoserver","status":"publish","type":"post","link":"https:\/\/www.fernandoquadro.com.br\/html\/2025\/09\/05\/importar-shapefile-para-postgis-via-api-rest-do-geoserver\/","title":{"rendered":"Importar shapefile para PostGIS via API Rest do GeoServer"},"content":{"rendered":"<p>Prezado leitor,<\/p>\n<p>Neste tutorial voc\u00ea vai aprender, passo a passo, como enviar um <strong>shapefile <\/strong>diretamente para o <strong>GeoServer <\/strong>usando a <strong>REST API<\/strong>. A diferen\u00e7a aqui \u00e9 que, em vez de o arquivo ser salvo na pasta data_dir, ele ser\u00e1 importado automaticamente para o <strong>PostGIS<\/strong>, utilizando o <strong>plugin Importer do GeoServer<\/strong>.<\/p>\n<p>Esse fluxo \u00e9 extremamente \u00fatil para automatizar processos de ingest\u00e3o de dados em ambientes de produ\u00e7\u00e3o, evitando a manipula\u00e7\u00e3o manual da pasta data_dir.<\/p>\n<p>Al\u00e9m disso, com a REST API, voc\u00ea pode integrar esse processo em scripts Python, pipelines de ETL ou at\u00e9 em rotinas de integra\u00e7\u00e3o cont\u00ednua (CI\/CD).<\/p>\n<p>Vamos ao passo a passo:<\/p>\n<p><strong>1. Cria\u00e7\u00e3o do Store<\/strong><\/p>\n<p>Antes de importar o shapefile, precisamos garantir que existe um store configurado apontando para o banco PostGIS.<\/p>\n<p>Isso pode ser feito pela pr\u00f3pria REST API, com o seguinte comando:<\/p>\n<pre>\r\ncurl  -u admin:geoserver -XPOST -H \"Content-type: application\/json\" -d @postgis.json \"http:\/\/localhost:8080\/geoserver\/rest\/workspaces\/cite\/datastores.json\"\r\n<\/pre>\n<p>O comando acima cria um novo Store no GeoServer, e as configura\u00e7\u00f5es ficam  no arquivo <strong>postgis.json<\/strong>, quem contem as informa\u00e7\u00f5es de conex\u00e3o da base de dados que voc\u00ea deseja utilizar no GeoServer, conforme o exemplo a abaixo:<\/p>\n<pre>\r\n{\r\n  \"dataStore\": {\r\n    \"name\": \"postgis\",\r\n    \"type\": \"PostGIS\",\r\n    \"workspace\": {\r\n      \"name\": \"cite\"\r\n    },\r\n    \"connectionParameters\": {\r\n      \"entry\": [\r\n        {\"@key\": \"schema\",\"$\": \"public\"},\r\n        {\"@key\": \"database\",\"$\": \"postgres\"},\r\n        {\"@key\": \"host\",\"$\": \"localhost\"},\r\n        {\"@key\": \"port\",\"$\": \"5432\"},\r\n        {\"@key\": \"passwd\",\"$\": \"postgres\"},\r\n        {\"@key\": \"dbtype\",\"$\": \"postgis\"},\r\n        {\"@key\": \"user\",\"$\": \"postgres\"},\r\n        {\"@key\": \"Estimated extends\",\"$\": \"true\"},\r\n        {\"@key\": \"encode functions\",\"$\": \"true\"},\r\n        {\"@key\": \"Loose bbox\",\"$\": \"true\"},\r\n        {\"@key\": \"Method used to simplify geometries\",\"$\": \"PRESERVETOPOLOGY\"},\r\n        {\"@key\": \"Support on the fly geometry simplification\",\"$\": \"true\"},\r\n        {\"@key\": \"validate connections\",\"$\": \"true\"},\r\n        {\"@key\": \"Connection timeout\",\"$\": \"20\"},\r\n        {\"@key\": \"min connections\",\"$\": \"1\"},\r\n        {\"@key\": \"max connections\",\"$\": \"10\"},\r\n        {\"@key\": \"Evictor tests per run\",\"$\": \"3\"},\r\n        {\"@key\": \"Test while idle\",\"$\": \"true\"},\r\n        {\"@key\": \"Max connection idle time\",\"$\": \"300\"}\r\n      ]\r\n    },\r\n    \"_default\": true\r\n  }\r\n}\r\n<\/pre>\n<p><strong>2. Defini\u00e7\u00e3o para importa\u00e7\u00e3o<\/strong><\/p>\n<p>\u00c9 importante ressaltar que para executar o comando abaixo, \u00e9 necess\u00e1rio que o <strong>plugin Importer<\/strong> esteja instalado no seu GeoServer, pois \u00e9 ele que far\u00e1 a importa\u00e7\u00e3o do shapefile para o banco de dados. O primeiro passo \u00e9 preparar a tarefa atrav\u00e9s do seguinte comando:<\/p>\n<pre>\r\ncurl.exe -u admin:geoserver -XPOST -H \"Content-type: application\/json\" -d @import.json \"http:\/\/localhost:8080\/geoserver\/rest\/imports\"\r\n<\/pre>\n<p>O arquivo <strong>import.json<\/strong> deve conter as informa\u00e7\u00f5es de onde voc\u00ea deseja armazenar o arquivo shapefile, no caso workspace e store:<\/p>\n<pre>\r\n{\r\n   \"import\": {\r\n      \"targetWorkspace\": {\r\n         \"workspace\": {\r\n            \"name\": \"cite\"\r\n         }\r\n      },\r\n      \"targetStore\": {\r\n         \"dataStore\": {\r\n            \"name\": \"postgis\"\r\n         }\r\n      }\r\n   }\r\n}\r\n<\/pre>\n<p>O comando acima ir\u00e1 retornar um ID (no nosso exemplo \u00e9 o 0), que voc\u00ea ir\u00e1 inserir no link de resposta ao GeoServer. Ap\u00f3s a execu\u00e7\u00e3o do comando acima temos uma importa\u00e7\u00e3o vazia, sem tarefas. Para adicionar uma tarefa, publique o shapefile na lista de tarefas:<\/p>\n<pre>\r\ncurl.exe -u admin:geoserver -F name=biomas_srv.zip -F filedata=@biomas_srv.zip \"http:\/\/localhost:8080\/geoserver\/rest\/imports\/0\/tasks\"\r\n<\/pre>\n<p><strong>3. Apontar para o Store<\/strong><\/p>\n<p>Como enviamos um shapefile, o importador assume que o destino ser\u00e1 um reposit\u00f3rio de shapefiles. Para importar para o PostGIS, precisaremos redefini-lo, e faremos isso atrav\u00e9s do arquivo <strong>target.json<\/strong>:<\/p>\n<pre>\r\n{\r\n  \"dataStore\": {\r\n    \"name\":\"postgis\"\r\n  }\r\n}\r\n<\/pre>\n<p>Coloque esse arquivo na requisi\u00e7\u00e3o abaixo:<\/p>\n<pre>\r\ncurl.exe -u admin:geoserver -XPUT -H \"Content-type: application\/json\" -d @target.json \"http:\/\/localhost:8080\/geoserver\/rest\/imports\/0\/tasks\/0\/target\"\r\n<\/pre>\n<p><strong>4. Realizar a importa\u00e7\u00e3o<\/strong><\/p>\n<p>Por fim, executamos a importa\u00e7\u00e3o enviando um POST da seguinte forma: <\/p>\n<pre>\r\ncurl.exe -u admin:geoserver -XPOST \"http:\/\/localhost:8080\/geoserver\/rest\/imports\/0\"\r\n<\/pre>\n<p>Se tudo correr bem, o shapefile ser\u00e1 carregado diretamente no seu banco PostGIS e publicado no GeoServer.<\/p>\n<p><strong>5. B\u00d4NUS<\/strong><\/p>\n<p>Para quem deseja automatizar o processo, segue um exemplo de um Script Python usando a biblioteca requests. Veja como usar:<\/p>\n<p>1. Salve o script em um arquivo, por exemplo import_shapefile.py.<br \/>\n2. Certifique-se de instalar a biblioteca necess\u00e1ria:<\/p>\n<pre>\r\npip install requests\r\n<\/pre>\n<p>3. Ajuste os par\u00e2metros de conex\u00e3o (usu\u00e1rio, senha, banco, shapefile, workspace etc.) conforme seu ambiente.<br \/>\n4. Agora execute o script: python import_shapefile.py<\/p>\n<pre>\r\n# Script import_shapefile.py\r\n\r\nimport requests\r\nimport json\r\n\r\n# Configura\u00e7\u00f5es\r\nGEOSERVER_URL = \"http:\/\/localhost:8080\/geoserver\/rest\"\r\nAUTH = (\"admin\", \"geoserver\")  # usu\u00e1rio e senha\r\nWORKSPACE = \"cite\"\r\nDATASTORE = \"postgis\"\r\nSHAPEFILE = \"biomas_srv.zip\"\r\n\r\n# 1. Criar o DataStore (caso ainda n\u00e3o exista)\r\npostgis_json = {\r\n    \"dataStore\": {\r\n        \"name\": DATASTORE,\r\n        \"type\": \"PostGIS\",\r\n        \"workspace\": {\"name\": WORKSPACE},\r\n        \"connectionParameters\": {\r\n            \"entry\": [\r\n                {\"@key\": \"schema\", \"$\": \"public\"},\r\n                {\"@key\": \"database\", \"$\": \"postgres\"},\r\n                {\"@key\": \"host\", \"$\": \"localhost\"},\r\n                {\"@key\": \"port\", \"$\": \"5432\"},\r\n                {\"@key\": \"passwd\", \"$\": \"postgres\"},\r\n                {\"@key\": \"dbtype\", \"$\": \"postgis\"},\r\n                {\"@key\": \"user\", \"$\": \"postgres\"}\r\n            ]\r\n        }\r\n    }\r\n}\r\n\r\nresp = requests.post(\r\n    f\"{GEOSERVER_URL}\/workspaces\/{WORKSPACE}\/datastores\",\r\n    auth=AUTH,\r\n    headers={\"Content-type\": \"application\/json\"},\r\n    data=json.dumps(postgis_json)\r\n)\r\n\r\nprint(\"Cria\u00e7\u00e3o do DataStore:\", resp.status_code)\r\n\r\n# 2. Criar importa\u00e7\u00e3o\r\nimport_json = {\r\n    \"import\": {\r\n        \"targetWorkspace\": {\"workspace\": {\"name\": WORKSPACE}},\r\n        \"targetStore\": {\"dataStore\": {\"name\": DATASTORE}}\r\n    }\r\n}\r\n\r\nresp = requests.post(\r\n    f\"{GEOSERVER_URL}\/imports\",\r\n    auth=AUTH,\r\n    headers={\"Content-type\": \"application\/json\"},\r\n    data=json.dumps(import_json)\r\n)\r\n\r\nimport_id = resp.json()[\"import\"][\"id\"]\r\nprint(\"ID da importa\u00e7\u00e3o:\", import_id)\r\n\r\n# 3. Adicionar o shapefile \u00e0 importa\u00e7\u00e3o\r\nwith open(SHAPEFILE, \"rb\") as f:\r\n    resp = requests.post(\r\n        f\"{GEOSERVER_URL}\/imports\/{import_id}\/tasks\",\r\n        auth=AUTH,\r\n        files={\"filedata\": f},\r\n        data={\"name\": SHAPEFILE}\r\n    )\r\n\r\nprint(\"Upload shapefile:\", resp.status_code)\r\n\r\n# 4. Ajustar destino para PostGIS\r\ntarget_json = {\"dataStore\": {\"name\": DATASTORE}}\r\n\r\nresp = requests.put(\r\n    f\"{GEOSERVER_URL}\/imports\/{import_id}\/tasks\/0\/target\",\r\n    auth=AUTH,\r\n    headers={\"Content-type\": \"application\/json\"},\r\n    data=json.dumps(target_json)\r\n)\r\n\r\nprint(\"Redefini\u00e7\u00e3o destino:\", resp.status_code)\r\n\r\n# 5. Executar importa\u00e7\u00e3o\r\nresp = requests.post(\r\n    f\"{GEOSERVER_URL}\/imports\/{import_id}\",\r\n    auth=AUTH\r\n)\r\n\r\nprint(\"Execu\u00e7\u00e3o da importa\u00e7\u00e3o:\", resp.status_code)\r\n\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Prezado leitor, Neste tutorial voc\u00ea vai aprender, passo a passo, como enviar um shapefile diretamente para o GeoServer usando a REST API. A diferen\u00e7a aqui \u00e9 que, em vez de o arquivo ser salvo na pasta data_dir, ele ser\u00e1 importado&#8230; <a class=\"more-link\" href=\"https:\/\/www.fernandoquadro.com.br\/html\/2025\/09\/05\/importar-shapefile-para-postgis-via-api-rest-do-geoserver\/\">Continue Reading &rarr;<\/a><\/p>\n","protected":false},"author":275,"featured_media":9910,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[24],"tags":[208,212,327],"class_list":["post-9906","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-gis","tag-geoserver","tag-postgis","tag-rest-api"],"_links":{"self":[{"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/posts\/9906","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/users\/275"}],"replies":[{"embeddable":true,"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/comments?post=9906"}],"version-history":[{"count":14,"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/posts\/9906\/revisions"}],"predecessor-version":[{"id":9921,"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/posts\/9906\/revisions\/9921"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/media\/9910"}],"wp:attachment":[{"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/media?parent=9906"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/categories?post=9906"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.fernandoquadro.com.br\/html\/wp-json\/wp\/v2\/tags?post=9906"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}