RU:API v0.6

From OpenStreetMap Wiki
Jump to: navigation, search
Доступные языки — API v0.6
· Afrikaans · Alemannisch · aragonés · asturianu · azərbaycanca · Bahasa Indonesia · Bahasa Melayu · Bân-lâm-gú · Basa Jawa · Baso Minangkabau · bosanski · brezhoneg · català · čeština · dansk · Deutsch · eesti · English · español · Esperanto · estremeñu · euskara · français · Frysk · Gaeilge · Gàidhlig · galego · Hausa · hrvatski · Igbo · interlingua · Interlingue · isiXhosa · isiZulu · íslenska · italiano · Kiswahili · Kreyòl ayisyen · kréyòl gwadloupéyen · Kurdî · latviešu · Lëtzebuergesch · lietuvių · magyar · Malagasy · Malti · Nederlands · Nedersaksies · norsk bokmål · norsk nynorsk · occitan · Oromoo · oʻzbekcha/ўзбекча · Plattdüütsch · polski · português · română · shqip · slovenčina · slovenščina · Soomaaliga · suomi · svenska · Tiếng Việt · Türkçe · Vahcuengh · vèneto · Wolof · Yorùbá · Zazaki · српски / srpski · беларуская · български · қазақша · македонски · монгол · русский · тоҷикӣ · українська · Ελληνικά · Հայերեն · ქართული · नेपाली · मराठी · हिन्दी · অসমীয়া · বাংলা · ਪੰਜਾਬੀ · ગુજરાતી · ଓଡ଼ିଆ · தமிழ் · తెలుగు · ಕನ್ನಡ · മലയാളം · සිංහල · ไทย · မြန်မာဘာသာ · ລາວ · ភាសាខ្មែរ · ⵜⴰⵎⴰⵣⵉⵖⵜ · አማርኛ · 한국어 · 日本語 · 中文(简体)‎ · 吴语 · 粵語 · 中文(繁體)‎ · ייִדיש · עברית · اردو · العربية · پښتو · سنڌي · فارسی · ދިވެހިބަސް

API v0.6 является последней версией OSM API опубликованной 17-21 апреля 2009.

Contents

Основная информация

Этот API основан на идеях RESTful API. Для дополнительной информации, касающейся RESTful API, смотрите wikipedia's Representational State Transfer page.

API — это компонент сервера, которому направляются REST запросы. REST запросы имеют вид HTTP GET, PUT, POST, или DELETE сообщений. Любые загружаемые данные имеют формат XML с использованием MIME-типа "text/xml" и кодировки UTF-8, и могут быть сжаты протоколом HTTP, если клиент указывает через HTTP заголовок "Accept", что может обрабатывать сжатые сообщения.

Запросы, изменяющие базу данных, требуют авторизации HTTP Basic Authorization или OAuth. Запросы на чтение не требуют авторизации (кроме чтения информации о пользователях).

Предварительный Full DTD (в процессе создания и обсуждения).

Отличия между API v0.5 и API v0.6

URL + Аутентификация

В настоящее время API доступен по следующей ссылке: http://api.openstreetmap.org/

Если вы хотите протестировать ваше программное обеспечение на совместимость с API, то используйте http://api06.dev.openstreetmap.org/ вместо выше указанного.

Все вызовы API которые обновляют, создают или удаляют данные должны делаться идентифицированным и авторизованным пользователем. Аутентификация осуществляется через HTTP Basic authentication с использованием логина и пароля, либо через OAuth.

Элементы

Существуют API вызовы на создание, чтение, обновление и удаление трёх базовых элементов, составляющих данные карты OpenStreetMap. Каждый из них возвращает или ожидает данные в формате XML.

Пакеты правок (Changesets)

Каждая модификация одного или более элементов должна ссылаться на открытый пакет правок.

Теги (tags)

Каждый элемент или пакет правок может иметь произвольное число тегов. Тег — это пара ключ-значение (Key-Value) Юникод-строк длиной до 255 символов (именно Юникод-символов, не байт).

Надёжная идентификация пользователей

Предыдущий API v0.5 возвращал только отображаемое имя пользователя. Пользователь мог изменить его в любое время и история такого изменения нигде не сохранялась. Это значит что не было способа надёжно идентифицировать пользователя который изменял какие-то данные.. API v0.6 включает в себя числовой user ID аккаунта в дополнение к отображаемому имени пользователя. Например:

<node id="68" ... user="fred" uid="123"/>

Это, однако, делает все пользовательские правки публичными. User ID для пользователей, которые в прошлом делали анонимные правки отображаться не будет. В соответствии с рекомендациями OpenStreetMap Foundation Board, анонимные правки больше не разрешаются.

Номера версий/Optimistic locking

Дамп планеты (the planet dump), различия (diffs) и API вызовы возвращают атрибут version для каждого из элементов Node, Way and Relation.

<node id="68" ... version="12"/>

Эти номера версий используются для optimistic locking. Чтобы загрузить новую версию объекта, клиент должен предоставить версию объекта, измененного им. Если версия предоставляемого объекта не равна версии этого объекта, хранящегося на сервере, сервер вернёт ошибку (HTTP status code 409: Conflict). Это означает, что каждый клиент, обновляющий данные сервера должен хранить номер версии исходных данных. Каждый элемент может быть обновлён сколь угодное количество раз в рамках одного пакета правок, и его версия каждый раз увеличивается, так что для какого-то элемента одного пакета правок может быть множество history versions.

Кроме того, клиенты могут теперь обращаться к конкретной версии элемента.

Номера версий всегда начинаются с 1 и увеличиваются на 1 при каждом изменении элемента. Клиенты не должны полагаться на автоматическое увеличение версии на единицу при обновлении элемента, вместо этого нужно извлекать номер новой версии из ответа сервера.

XML формат

Каждый XML ответ сервера обернут в элемент <osm>, если не указано иное (например, при загрузке различий (diffs) или скачивая пакет правок (changesets)). В большинстве последующих примеров такая обёртка не указывается, но подразумевается что она есть.

<osm version="0.6" generator="OpenStreetMap server">
  ...
  ...
</osm>

Каждый вызов API должен быть обернут элементом <osm>, но аттрибуты version и generator могут быть опущены.

Замена корректных HTTP методов

Многие API вызовы используют методы PUT и DELETE, которые могут не поддерживаться HTTP стеком клиента, который вы используете. Вы должны сообщить авторам данного стека, что их реализация HTTP является неполной. Иначе вам необходимо добавить заголовок X_HTTP_METHOD_OVERRIDE со значением метода, который вы хотите симулировать. Например, чтобы заставить curl сделать POST, но используя обработчик PUT, надо:

curl -v -v -d @changeset.osm -H "X_HTTP_METHOD_OVERRIDE: PUT" "http://server/api/0.6/changeset/create"

API вызовы

Разное

Возможности: GET /api/capabilities

Данный вызов API предназначен для предоставления клиенту информации о возможностях и ограничениях текущей версии API.

Ответ сервера

Возвращает документ XML (тип содержимого text/xml)

 <osm version="0.6" generator="OpenStreetMap server">
   <api>
     <version minimum="0.6" maximum="0.6"/>
     <area maximum="0.25"/>
     <tracepoints per_page="5000"/>
     <waynodes maximum="2000"/>
     <changesets maximum_elements="50000"/>
     <timeout seconds="300"/>
   </api>
 </osm>

Заметьте, что реальные возвращаемые значения могут измениться в любой момент, поэтому данный документ приводится лишь в качестве примера.

  • version — минимальная и максимальная версия API вызовов, которые принимает сервер.
  • area — максимальная область в квадратных градусах, которая может быть запрошена посредством API вызова.
  • tracepoints — точки трека на страницу. Максимальное количество точек одного GPS трека.
  • waynodes — максимальное количество точек в путях.
  • changesets — максимальное количество элементов (узлов, путей и отношений) в пакете правок.

Примечания

  • Заметьте, что в URL не указывается версия. Для удобства сервер также поддерживает запрос /api/0.6/capabilities, так что клиенты могут использовать префикс URL http:/.../api/0.6 для всех запросов.

Извлечение картографических данных ограниченных прямоугольником (bounding box): GET /api/0.6/map

Следующая команда возвращает:

  • Все узлы, находящиеся внутри заданного прямоугольника, и любые отношения, которые ссылаются на них.
  • Все пути, которые ссылаются на хотя бы один узел внутри заданного прямоугольника, любые отношения, которые ссылаются на них (на пути), и все узлы снаружи ограничительного прямоугольника, которые входят в эти пути.
  • Все отношения, которые ссылаются на каждый из узлов или путей, включённых по вышеуказанным правилам (но не рекурсивно).
GET /api/0.6/map?bbox=left,bottom,right,top

где:

  • left долгота левого края прямоугольника (самая западная).
  • bottom широта нижнего (самого южного) края прямоугольника.
  • right долгота правого края прямоугольника (самая восточная).
  • top широта верхнего края прямоугольника (самая северная).

Заметьте что, несмотря на то, что эта команда возвращает те отношения, которые ссылаются на вышеупомянутые узлы и пути, обратное неверно: она не возвращает все узлы и пути на которые ссылаются эти отношения. Это предотвращает необоснованно большой результирующий набор. Например, представьте себе случай, когда:

  • Есть отношение "Russia", которое ссылается на каждый узел в России.
  • Узлы, пути и отношения извлекаются ограничительным прямоугольником, охватывающим лишь небольшой кусочек России.

Хотя результат будет включать узлы, пути и отношения, определённые правилами для этой команды, включая отношение "Russia", в то же время он не будет включать в себя каждый узел и путь России. По желанию, узлы и пути, на которые ссылается отношение "Russia", можно получить по их ID, хранящихся в этом отношении, с помощью соответствующего API вызова.

Также учтите, что пути пересекающие прямоугольник, но не имеющие узлов внутри него, в результат не входят.

Коды ошибок

HTTP status code 400 (Bad Request)
Когда превышено любое ограничение на количество запрошенных узлов/путей/отношений
HTTP status code 509 (Bandwidth Limit Exceeded)
"Ошибка: Вы загружаете слишком много данных. Пожалуйста, повторите попытку позже." См. Developer FAQ.

Пакеты правок

Для облегчения идентификации вносимых изменений существует концепция пакетов правок. Каждое изменение стандартных элементов OSM должно ссылаться на открытый пакет правок, который подобно другим элементам может содержать теги. Для пакетов правок рекомендуется тег с ключом comment=*, содержащий короткое описание изменений, сделанных в рамках пакета. Новый пакет правок может быть открыт в любое время, и на него могут ссылаться несколько API вызовов. Это значит, что пакет может быть закрыт вручную, т.к. сервер на самом деле не знает, когда заканчивается одна серия правок и когда должна начаться другая. Также во избежание накопления незакрытых пакетов правок существует механизм автоматического закрытия пакетов, который следует следующим правилам:

Changesets are specifically not atomic — elements added within a changeset will be visible to other users before the changeset is closed. Given how many changes might be uploaded in one step it's not feasible. Instead optimistic locking is used as described above. Anything submitted to the server in a single request will be considered atomically. To achieve transactionality for multiple changes there is the new diff upload API call.

Changesets facilitate the implementation of rollbacks. By providing insight into the changes committed by a single person it becomes easier to identify the changes made, rather than just rolling back a whole region. Direct support for rollback will not be in the API, instead they will be a form of reverse merging, where client can download the changeset, examine the changes and then manipulate the API to obtain the desired results. Rolling back a changeset can be be an extremely complex process especially if the rollback conflicts with other changes made in the mean time; we expect (hope) that in time, expert applications will be created that make rollback on various levels available to the average user.

To support easier usage, the server stores a bounding box for each changeset and allows users to query changesets in an area. This will be calculated by the server, since it needs to look up the relevant nodes anyway. As an optimisation the server will create a buffer slightly larger than the objects to avoid having to update the bounding box too often. Client should note that if people make many small changes in a large area they will be easily matched. In this case clients should examine the changeset directly to see if it truly overlaps. A client can expand the bounding box manually using an API call, which can be useful when the client already knows the full extent of the data it is about to upload.

It is not possible to delete changesets at the moment, even if they don't contain any changes. The server may at a later time delete changesets which are closed and which do not contain any changes. This is not yet implemented.

Bounding box computation

This is how the API computes the bounding box associated with a changeset:

  • Nodes: Any change to a node, including deletion, adds the node's old and new location to the bbox.
  • Ways: Any change to a way, including deletion, adds all of the way's nodes to the bbox.
  • Relations:
  • adding or removing nodes or ways from a relation causes them to be added to the changeset bounding box.
  • adding a relation member or changing tag values causes all node and way members to be added to the bounding box.
  • this is similar to how the map call does things and is reasonable on the assumption that adding or removing members doesn't materially change the rest of the relation.

Create: PUT /api/0.6/changeset/create

The payload of a changeset creation request has to be one or more changeset elements optionally including an arbitrary number of tags.

<osm>
  <changeset>
    <tag k="created_by" v="JOSM 1.61"/>
    <tag k="comment" v="Just adding some streetnames"/>
    ...
  </changeset>
  ...
</osm>

If there are multiple changeset elements in the XML the tags from all of them are used, later ones overriding the earlier ones in case of duplicate keys.

Ответ сервера

The ID of the newly created changeset with a content type of text/plain

Коды ошибок

HTTP status code 400 (Bad Request)
When there are errors parsing the XML
HTTP status code 405 (Method Not Allowed)
If the request is not a HTTP PUT request

Примечания

Any number of possibly editor-specific, tags are allowed. An editor might, for example, automatically include information about which background image was used, or even a bit of internal state information that will make it easier to revisit the changeset with the same editor later, etc.

Clients should include a created_by=* tag. Clients are advised to make sure that a comment=* is present, which the user has entered. It is optional at the moment but this might change in later API versions. Clients should not automatically generate the comment tag, as this tag is for the end-user to describe their changes. Clients may add any other tags as they see fit.

Read: GET /api/0.6/changeset/#id

Returns the changeset with the given id in OSM-XML format.

<osm>
  <changeset id="10" user="fred" uid="123" created_at="2008-11-08T19:07:39+01:00" open="true" min_lon="7.0191821" min_lat="49.2785426" max_lon="7.0197485" max_lat="49.2793101">
    <tag k="created_by" v="JOSM 1.61"/>
    <tag k="comment" v="Just adding some streetnames"/>
    ...
 </changeset>
</osm>

Параметры

id
Номер (id) требуемого пакета правок

Ответ сервера

Returns the single changeset element containing the changeset tags with a content type of text/xml

Коды ошибок

HTTP status code 404 (Not Found)
Когда пакет правок с заданным номером не найден

Примечания

  • The uid might not be available for changesets auto generated by the API v0.5 to API v0.6 transition?
  • The bounding box attributes will be missing for an empty changeset.
  • The changeset bounding box is a rectangle that contains the bounding boxes of all objects changed in this changeset. It is not necessarily the smallest possible rectangle that does so.
  • This API call only returns information about the changeset itself but not the actual changes made to elements in this changeset. To access this information use the download API call.

Update: PUT /api/0.6/changeset/#id

For updating tags on the changeset, e.g. changeset comment=foo.

Payload should be an OSM document containing the new version of a single changeset. Bounding box, update time and other attributes are ignored and cannot be updated by this method. For updating the bounding box see the expand_bbox method.

<osm>
  <changeset>
    <tag k="comment" v="Just adding some streetnames and a restaurant"/>
  </changeset>
</osm>

Параметры

id
The id of the changeset to update. The user issuing this API call has to be the same that created the changeset

Ответ сервера

An OSM document containing the new version of the changeset with a content type of text/xml

Коды ошибок

HTTP status code 400 (Bad Request)
When there are errors parsing the XML
HTTP status code 404 (Not Found)
When no changeset with the given id could be found
HTTP status code 405 (Method Not Allowed)
If the request is not a HTTP PUT request
HTTP status code 409 (Conflict) — text/plain
If the changeset in question has already been closed (either by the user itself or as a result of the auto-closing feature). A message with the format "The changeset #id was closed at #closed_at." is returned
Or if the user trying to update the changeset is not the same as the one that created it

Примечания

Unchanged tags have to be repeated in order to not be deleted.

Close: PUT /api/0.6/changeset/#id/close

Closes a changeset. A changeset may already have been closed without the owner issuing this API call. In this case an error code is returned.

Параметры

id
The id of the changeset to close. The user issuing this API call has to be the same that created the changeset.

Ответ сервера

Nothing is returned upon successful closing of a changeset (HTTP status code 200)

Коды ошибок

HTTP status code 404 (Not Found)
When no changeset with the given id could be found
HTTP status code 405 (Method Not Allowed)
If the request is not a HTTP PUT request
HTTP status code 409 (Conflict) — text/plain
If the changeset in question has already been closed (either by the user itself or as a result of the auto-closing feature). A message with the format "The changeset #id was closed at #closed_at." is returned
Or if the user trying to update the changeset is not the same as the one that created it

Download: GET /api/0.6/changeset/#id/download

Returns the OsmChange document describing all changes associated with the changeset.

Параметры

id
The id of the changeset for which the OsmChange is requested.

Ответ сервера

The OsmChange XML with a content type of text/xml.

Коды ошибок

HTTP status code 404 (Not Found)
When no changeset with the given id could be found

Примечания

  • The result of calling this may change as long as the changeset is open.
  • The elements in the OsmChange are sorted by timestamp and version number.

Expand Bounding Box: POST /api/0.6/changeset/#id/expand_bbox

POSTing a XML document containing node elements (these node elements have nothing to do with the Nodes mentioned elsewhere in this page, they are merely a container for lat and lon attributes) that are to this location will cause the bounding box of the changeset to expand to exactly the smallest containing rectangle of the points given and the bounding box automatically calculated by the API. So this call can only increase the size of the bounding box and later additions to the changeset may override the expanded bounding box.

The input document should look like this:

<osm>
  <node lat=".." lon=".."/>
  <node lat=".." lon=".."/>
  ...
</osm>

The osm element may contain other elements than node, but these are ignored. The node element may contain other attributes (including id) than lat and lon, but these are ignored as well.

This call is supported to give editors the chance to expand the bounding box that the API automatically computes for the changeset. There are cases where the editor will have extra knowledge that make it advisable to flag a larger area as changed than the API would guess from the changes alone. This call may also be used before uploading a large number of changes as a hint for the server which area will be affected.

Параметры

id
The id of the changeset for which the OsmChange is requested.

Ответ сервера

Returns the updated changeset containing with a content type of text/xml.

Коды ошибок

HTTP status code 404 (Not Found)
When no changeset with the given id could be found
HTTP status code 409 (Conflict) — text/plain
If the changeset in question has already been closed (either by the user itself or as a result of the auto-closing feature). A message with the format "The changeset #id was closed at #closed_at." is returned
Or if the user trying to update the changeset is not the same as the one that created it

Примечания

  • I don't know if there are really any advantages in issuing a expand_bbox call before a large chunk of changes is uploaded.
  • As the reuse of node as a XML element name is confusing and the format of this call might change in a later API version.

Query: GET /api/0.6/changesets

This is an API method for querying changesets. It supports querying by different criteria.

Where multiple queries are given the result will be those which match all of the requirements. The contents of the returned document are the changesets and their tags. To get the full set of changes associated with a changeset, use the download method on each changeset ID individually.

Modification and extension of the basic queries above may be required to support rollback and other uses we find for changesets.

Параметры

bbox=min_lon,min_lat,max_lon,max_lat (W,S,E,N)
Find changesets within the given bounding box
user=#uid or display_name=#name
Find changesets by the user with the given user id or display name. Providing both is an error.
time=T1
Find changesets closed after T1
time=T1,T2
Find changesets that were closed after T1 and created before T2
open
Only finds changesets that are still open but excludes changesets that are closed or have reached the element limit for a changeset (50.000 at the moment)
closed
Only finds changesets that are closed or have reached the element limit

Time format: Anything that this Ruby function will parse. The default str is ’-4712-01-01T00:00:00+00:00’; this is Julian Day Number day 0.

Ответ сервера

Returns a list of all changeset ordered by creation date. The <osm> element may be empty if there were no results for the query. The response is send with a content type of text/xml.

Коды ошибок

HTTP status code 400 (Bad Request) — text/plain
On misformed parameters. A text message explaining the error is returned. In particular, trying to provide both the UID and display name as user query parameters will result in this error.
HTTP status code 404 (Not Found)
When no user with the given uid or display_name could be found.

Примечания

  • Only changesets by public users are returned.
  • I'm not sure if the time query makes sense as it is implemented now. The original documentation for this feature states:
    • One-sided to query changesets where the start time is after the given time.
    • Bounded (?time=T1,T2) to query where the start time is between the given times.
  • Returns at most 100 changesets

Diff upload: POST /api/0.6/changeset/#id/upload

With this API call files in the OsmChange format can be uploaded to the server. This is guaranteed to be running in a transaction. So either all the changes are applied or none.

To upload an OSC file it has to conform to the OsmChange specification with the following additions:

  • each element must carry a changeset and a version attribute, except when you are creating an element where the version is not required as the server sets that for you. The changeset must be the same as the changeset ID being uploaded to.
  • a <delete> block in the OsmChange document may have an if-unused attribute (the value of which is ignored). If this attribute is present, then the delete operation(s) in this block are conditional and will only be executed if the object to be deleted is not used by another object. Without the if-unused, such a situation would lead to an error, and the whole diff upload would fail.

Параметры

id
The ID of the changeset this diff belongs to.
POST data
The OsmChange file data

Ответ сервера

If a diff is successfully applied a XML (content type text/xml) is returned in the following format

<diffResult generator="OpenStreetMap Server" version="0.6">
  <node|way|relation old_id="#" new_id="#" new_version="#"/>
  ...
</diffResult>

with one element for every element in the upload. Note that this can be counter-intuitive when the same element has appeared multiple times in the input then it will appear multiple times in the output.

Attribute create modify delete
old_id same as uploaded element.
new_id new ID same as uploaded not present
new_version new version not present

Коды ошибок

HTTP status code 400 (Bad Request) — text/plain
When there are errors parsing the XML. A text message explaining the error is returned.
When an placeholder ID is missing or not unique
HTTP status code 405 (Method Not Allowed)
If the request is not a HTTP POST request
HTTP status code 409 (Conflict) — text/plain
If the changeset in question has already been closed (either by the user itself or as a result of the auto-closing feature). A message with the format "The changeset #id was closed at #closed_at." is returned
If, while uploading, the max. size of the changeset is exceeded. A message with the format "The changeset #id was closed at #closed_at." is returned
Or if the user trying to update the changeset is not the same as the one that created it
Or if the diff contains elements with changeset IDs which don't match the changeset ID that the diff was uploaded to
Any of the error codes that could occur an a create, update or delete operation for one of the elements
See the according sections in this page

Примечания

  • Processing stops at the first error, so if there are multiple conflicts in one diff upload, only the first problem is reported.
  • There is currently no limit in the diff size but this will probably be changed later.

Changeset summary

The procedure for successful creation of a changeset is summarized in the following picture:

OSM API0.6 Changeset successful creation V0.1.png /changeset>

Elements

There are create, read, update and delete calls for all of the three basic elements in OpenStreetMap (Nodes, Ways and Relations). These calls are very similar except for the payload and a few special error messages so they are documented only once.

Create: PUT /api/0.6/[node|way|relation]/create

Creates a new element of the specified type. Note that the entire request should be wrapped in a
<osm>...</osm>
element.

A Node:

<osm>
 <node changeset="12" lat="..." lon="...">
   <tag k="note" v="Just a node"/>
   ...
 </node>
</osm>

A Way:

<osm>
 <way changeset="12">
   <tag k="note" v="Just a way"/>
   ...
   <nd ref="123"/>
   <nd ref="4345"/>
   ...
 </way>
</osm>

A Relation:

<osm>
 <relation changeset="12">
   <tag k="note" v="Just a relation"/>
   ...
   <member type="node" role="stop" ref="123"/>
   <member type="way" ref="234"/>
 </relation>
</osm>

If multiple elements are provided only the first is created. The rest is discarded (this behaviour differs from changeset creation).

Ответ сервера

The ID of the newly created element (content type is text/plain)

Коды ошибок

HTTP status code 400 (Bad Request) — text/plain
When there are errors parsing the XML. A text message explaining the error is returned.
When a changeset ID is missing (unfortunately the error messages are not consistent)
When a node is outside the world
When there are too many nodes for a way
HTTP status code 405 (Method Not Allowed)
If the request is not a HTTP PUT request
HTTP status code 409 (Conflict) — text/plain
If the changeset in question has already been closed (either by the user itself or as a result of the auto-closing feature). A message with the format "The changeset #id was closed at #closed_at." is returned
Or if the user trying to update the changeset is not the same as the one that created it
HTTP status code 412 (Precondition Failed)
When a way has nodes that do not exist or are not visible (i.e. deleted): "Way #{id} requires the nodes with id in (#{missing_ids}), which either do not exist, or are not visible."
When a relation has elements that do not exist or are not visible: "Relation with id #{id} cannot be saved due to #{element} with id #{element.id}"

Примечания

  • This updates the bounding box of the changeset.
  • The role attribute for relations is optional. An empty string is the default.

Read: GET /api/0.6/[node|way|relation]/#id

Returns the XML representation of the element.

Ответ сервера

XML representing the element, wrapped in an <osm> element:

<osm>
 <node id="123" lat="..." lon="..." version="142" changeset="12" user="fred" uid="123" visible="true" timestamp="2005-07-30T14:27:12+01:00">
   <tag k="note" v="Just a node"/>
   ...
 </node>
</osm>

Коды ошибок

HTTP status code 404 (Not Found)
When no element with the given id could be found
HTTP status code 410 (Gone)
If the element has been deleted

Update: PUT /api/0.6/[node|way|relation]/#id

Updates data from a preexisting element. A full representation of the element as it should be after the update has to be provided. So any tags that remain unchanged have to be in the update as well. A version number has to be provided as well.

Ответ сервера

Returns the new version number with a content type of text/plain.

Коды ошибок

HTTP status code 400 (Bad Request) — text/plain
When there are errors parsing the XML. A text message explaining the error is returned. This can also happen if you forget to pass the Content-Length header.
When a changeset ID is missing (unfortunately the error messages are not consistent)
When a node is outside the world
When there are too many nodes for a way
When the version of the provided element does not match the current database version of the element
HTTP status code 409 (Conflict) — text/plain
If the changeset in question has already been closed (either by the user itself or as a result of the auto-closing feature). A message with the format "The changeset #id was closed at #closed_at." is returned
Or if the user trying to update the changeset is not the same as the one that created it
HTTP status code 404 (Not Found)
When no element with the given id could be found
HTTP status code 412 (Precondition Failed)
When a way has nodes that do not exist or are not visible (i.e. deleted): "Way #{id} requires the nodes with id in (#{missing_ids}), which either do not exist, or are not visible."
When a relation has elements that do not exist or are not visible: "Relation with id #{id} cannot be saved due to #{element} with id #{element.id}"

Примечания

  • This updates the bounding box of the changeset.

Delete: DELETE /api/0.6/[node|way|relation]/#id

Expects a valid XML representation of the element to be deleted.

For example:

<osm>
 <node id="..." version="..." changeset="..."/>
</osm>

Where the node ID in the XML must match the ID in the URL, the version must match the version of the element you downloaded and the changeset must match the ID of an open changeset owned by the current authenticated user. It is allowed, but not necessary, to have tags on the element.

Ответ сервера

Returns the new version number with a content type of text/plain.

Коды ошибок

HTTP status code 400 (Bad Request) — text/plain
When there are errors parsing the XML. A text message explaining the error is returned.
When a changeset ID is missing (unfortunately the error messages are not consistent)
When a node is outside the world
When there are too many nodes for a way
When the version of the provided element does not match the current database version of the element
HTTP status code 404 (Not Found)
When no element with the given id could be found
HTTP status code 409 (Conflict) — text/plain
If the changeset in question has already been closed (either by the user itself or as a result of the auto-closing feature). A message with the format "The changeset #id was closed at #closed_at." is returned
Or if the user trying to update the changeset is not the same as the one that created it
HTTP status code 410 (Gone)
If the element has been already been deleted
HTTP status code 412 (Precondition Failed)
When a node is still used by a way: Node #{id} is still used by way #{way.id}.
When a node is still member of a relation: Node #{id} is still used by relation #{relation.id}.
When a way is still member of a relation: Way #{id} still used by relation #{relation.id}.
When a relation is still member of another relation: The relation #{id} is used in relation #{relation.id}.

Примечания

  • In earlier API versions no payload was required. It is needed now because of the need for changeset IDs and version numbers.

History: GET /api/0.6/[node|way|relation]/#id/history

Retrieves all old versions of an element. The old versions are not guaranteed to be ordered in any way.

Коды ошибок

HTTP status code 404 (Not Found)
When no element with the given id could be found

Version: GET /api/0.6/[node|way|relation]/#id/#version

Retrieves a specific version of the element.

Коды ошибок

HTTP status code 404 (Not Found)
When no element with the given id could be found

Multi fetch: GET /api/0.6/[nodes|ways|relations]

Allows a user to fetch multiple elements at once.

Параметры

[nodes|ways|relations]=comma separated list
The parameter has to be the same in the URL (e.g. /api/0.6/nodes?nodes=123,456,789)

Коды ошибок

HTTP status code 400 (Bad Request)
On a malformed request (parameters missing or wrong)
HTTP status code 404 (Not Found)
If one of the elements could not be found
HTTP status code 414 (Request-URI Too Large)
If the URI was too long (How long is too long?)

Relations for Element: GET /api/0.6/[node|way|relation]/#id/relations

Returns a XML document containing all (not deleted) relations in which the given element is used.

Примечания

  • There is no error if the element does not exist.
  • If the element does not exist or it isn't used in any relations an empty XML document is returned (apart from the <osm> elements)

Ways for Node: GET /api/0.6/node/#id/ways

Returns a XML document containing all the (not deleted) ways in which the given node is used.

Примечания

  • There is no error if the node does not exist.
  • If the node does not exist or it isn't used in any ways an empty XML document is returned (apart from the <osm> elements)

Full: GET /api/0.6/[way|relation]/#id/full

This API call retrieves a way or relation and all other elements referenced by it

  • For a way, it will return the way specified plus the full XML of all nodes referenced by the way.
  • For a relation, it will return the following:
    • The relation itself
    • All nodes, ways, and relations that are members of the relation
    • Plus all nodes used by ways from the previous step
    • The same recursive logic is not applied to relations. This means: If relation r1 contains way w1 and relation r2, and w1 contains nodes n1 and n2, and r2 contains node n3, then a "full" request for r1 will give you r1, r2, w1, n1, and n2. Not n3.

Коды ошибок

HTTP status code 404 (Not Found)
When no element with the given id could be found
HTTP status code 410 (Gone)
If the element has been deleted

Треки GPS

Получение точек GPS

Следующая команда возвращеет, в формате GPX, точки треков GPS, находящиеся внутри заданного прямоугольника.

GET /api/0.6/trackpoints?bbox=left,bottom,right,top&page=pageNumber

где:

  • left, bottom, right, and top are used the same way as they are in the command to retrieve nodes, ways, and relations.
  • pageNumber specifies which group of 5,000 points, or page, to return. Since the command does not return more than 5,000 points at a time, this parameter must be incremented—and the command sent again (using the same bounding box)—in order to retrieve all of the points for a bounding box that contains more than 5,000 points. When this parameter is 0 (zero), the command returns the first 5,000 points; when it is 1, the command returns points 5,001–10,000, etc.

Примеры

Retrieve the first 5,000 points for a bounding box:

http://api.openstreetmap.org/api/0.6/trackpoints?bbox=0,51.5,0.25,51.75&page=0

Retrieve the next 5,000 points (points 5,001–10,000) for the same bounding box:

http://api.openstreetmap.org/api/0.6/trackpoints?bbox=0,51.5,0.25,51.75&page=1


Uploading Traces

You can upload a GPX file or archive of GPX files through the API:

POST /api/0.6/gpx/create

This is the only API call using the POST method. It expects the following POST parameters in a multipart/form-data HTTP message:

parameter description
file The GPX file containing the track points. Note that for successful processing, the file must contain trackpoints (<trkpt>), not only waypoints, and the trackpoints must have a valid timestamp. Since the file is processed asynchronously, the call will complete successfully even if the file cannot be processed. The file may also be a .tar, .tar.gz or .zip containing multiple gpx files, although it will appear as a single entry in the upload log.
description The trace description.
tags A string containing tags for the trace.
public 1 if the trace is public, 0 if not. This exists for backwards compatibility only — the visibility parameter should now be used instead. This value will be ignored if visibility is also provided.
visibility One of the following: private, public, trackable, identifiable (for explanations see OSM trace upload page or Visibility of GPS traces)

HTTP basic authentication is required.

Downloading Trace Metadata

You access a GPX file's details and download the full file:

GET /api/0.6/gpx/<id>/details
GET /api/0.6/gpx/<id>/data

HTTP basic authentication is required, although theoretically these calls should be allowed without authentication if the trace is marked public. If the trace is not public, only the owner may access the data.

Example "details" response:

<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="OpenStreetMap server">
  <gpx_file id="836619" name="track.gpx" lat="52.0194" lon="8.51807" 
            user="Hartmut Holzgraefe" visibility="public" pending="false"  
            timestamp="2010-10-09T09:24:19Z">
    <description>PHP upload test</description>
    <tag>test</tag>
    <tag>php</tag>
  </gpx_file>
</osm>

The "data" response will be the exact file uploaded.


You can also get a list of all the GPX traces for the authenticated user using:

GET /api/0.6/user/gpx_files

Methods for User Data

Unless noted otherwise, all user-specific API calls require authentication and operate on the currently authenticated user account. That's why they don't normally have an explicit "username" parameter.

Details

You can get the home location and the displayname of the user, by using

GET /api/0.6/user/details

this returns an XML document of the from

<osm version="0.6" generator="OpenStreetMap server">
 <user display_name="Max Muster" account_created="2006-07-21T19:28:26Z" id="1234">
   <home lat="49.4733718952806" lon="8.89285988577866" zoom="3"/>
   <description>The description of your profile</description>
   <languages>
     <lang>de-DE</lang>
     <lang>de</lang>
     <lang>en-US</lang>
     <lang>en</lang>
   </languages>
 </user>
</osm>

Preferences

The OSM server supports storing arbitrary user preferences. This can be used by editors, for example, to offer the same configuration wherever the user logs in, instead of a locally-stored configuration.

You can retrieve the list of current preferences using

 GET /api/0.6/user/preferences

this returns an XML document of the form

  <osm version="0.6" generator="OpenStreetMap server">
    <preferences>
       <preference k="somekey" v="somevalue" />
       ...
    </preferences>
  </osm>

The same structure can be used to upload preferences (using the PUT method instead of GET). All existing preferences are replaced by the newly uploaded set.

Also possible is to PUT a single preference using

 PUT /api/0.6/user/preferences/[your_key] (without the brackets)

in this instance, the payload of the request should only contain the value of the preference, i.e. not XML formatted.

The PUT call returns HTTP response code 406 (not acceptable) if the same key occurs more than once, and code 413 (request entity too large) if you try to upload more than 150 preferences at once. The sizes of the key and value are limited to 255 characters.

Further Reading