Přeskočit obsah
For the complete DHIS2 documentation index, see llms.txt.

Přehled

Web API je komponenta, která umožňuje externím systémům přistupovat k datům uloženým v instanci DHIS2 a manipulovat s nimi. Přesněji řečeno, poskytuje programové rozhraní k široké škále vystavených dat a metod služeb pro aplikace, jako jsou softwaroví klienti třetích stran, webové portály a interní moduly DHIS2.

Úvod

The Web API adheres to many of the principles behind the REST architectural style. To mention some important ones:

  1. Základní stavební kameny se označují jako zdroje. Zdrojem může být cokoli vystavené na webu, od dokumentu po obchodní proces – cokoliv, s čím by klient mohl chtít interagovat. Informační aspekty zdroje lze vyhledávat nebo vyměňovat prostřednictvím zdrojů reprezentací. Reprezentace je pohled na a resource's state at any given time. For instance, the visualizations resource in DHIS2 represents visualizations of aggregated data for je určitý soubor parametrů. Tento zdroj lze získat v variety of representation formats including JSON and CSV.
  2. Všechny zdroje lze jednoznačně identifikovat pomocí URI (také odkazováno to as URL). All resources have a default representation. You can uvést, že máte zájem o konkrétní zastoupení podle poskytnutí Accept HTTP hlavičky, přípony souboru nebo formátu query parameter. So in order to retrieve a CSV representation of an analytics data response you can supply an Accept: application/csv header or append .csv or ?format=csv to your request URL.
  3. Interactions with the API requires the correct use of HTTP methods or slovesa. To znamená, že pro zdroj musíte vydat GET požadavek, když jej chcete získat, požadavek POST, když chcete chcete-li jej vytvořit, PUT, když jej chcete aktualizovat, a DELETE, když you want to remove it.

Ověření

The DHIS2 Web API supports three protocols for authentication:

You can verify and get information about the currently authenticated user by making a GET request to the following URL:

/api/33/me

And more information about authorities (and if a user has a certain authority) by using the endpoints:

/api/33/me/authorities
/api/33/me/authorities/ALL

Základní ověřování

The DHIS2 Web API supports Basic authentication. Basic authentication is a technique for clients to send login credentials over HTTP to a web server. Technically speaking, the username is appended with a colon and the password, Base64-encoded, prefixed Basic and supplied as the value of the Authorization HTTP header. More formally that is:

Autorizace: Základní base64encode(username:password)

Most network-aware development environments provide support for Basic authentication, such as Apache HttpClient and Spring RestTemplate. An important note is that this authentication scheme provides no security since the username and password are sent in plain text and can be easily observed by an attacker. Using Basic is recommended only if the server is using SSL/TLS (HTTPS) to encrypt communication with clients. Consider this a hard requirement in order to provide secure interactions with the Web API.

Dvoufaktorové ověřování

DHIS2 supports two-factor authentication. This can be enabled per user. When enabled, users will be asked to enter a 2FA code when logging in. You can read more about 2FA here.

Osobní přístupový token

Personal access tokens (PATs) are an alternative to using passwords for authentication to DHIS2 when using the API.

PATs can be a more secure alternative to HTTP Basic Authentication, and should be your preferred choice when creating a new app/script etc.

HTTP Basic Authentication is considered insecure because, among other things, it sends your username and password in clear text. It may be deprecated in future DHIS2 versions or made opt-in, meaning that basic authentication would need to be explicitly enabled in the configuration.

Important security concerns!

Your PATs will automatically inherit all the permissions and authorizations your user has. It is therefore extremely important that you limit the access granted to your token depending on how you intend to use it, see Configuring your token.

If you only want the token to have access to a narrow and specific part of the server, it is advised to rather create a new special user that you assign only the roles/authorities you want it to have access to.

Creating a token

Chcete-li vytvořit nový PAT, máte dvě možnosti: * A. Vytvořte token v uživatelském rozhraní na stránce profilu vašeho účtu. * B. Vytvořte token prostřednictvím rozhraní API.

A. Creating a token on the account's page

Log in with your username and password, go to your profile page (Click top right corner, and chose "Edit profile" from the dropdown). On your user profile page, choose "Personal access tokens" from the left side menu. You should now be on the "Manage personal access tokens" page and see the text: "You don't have any active personal access tokens". Click "Generate new token" to make a new token. A "Generate new token" popup will be shown and present you with two choices:

1. Server/script context:

"Tento typ se používá pro integrace a skripty, ke kterým nebude mít prohlížeč přístup."

If you plan to use the token in an application, a script or similar, this type should be your choice.

2. Browser context:

"Tento typ se používá pro aplikace, jako jsou veřejné portály, ke kterým bude přístup pomocí webového prohlížeče."

If you need to link to DHIS2 on a webpage, or e.g. embed in an iframe, this is probably the type of token you want.

Configuring your token

After choosing what token type you want, you can configure different access constraints on your token. By constraint, we mean how to limit and narrow down how your token can be used. This can be of crucial importance if you plan on using the token in a public environment, e.g. on a public dashboard on another site, embedded in an iframe. Since tokens always have the same access/authorities that your user currently has, taking special care is needed if you intend to use it in any environment you don't have 100% control over.

NB: If anyone else gets their hands on your token, they can do anything your user can do. It is not possible to distinguish between actions performed using the token and other actions performed by your user.

Important: It is strongly advised that you create a separate unique user with only the roles/authorities you want the token to have if you plan on using PAT tokens in a non-secure and/or public environment, e.g. on a PC or server, you don't have 100% control over, or "embedded" in a webpage on another server.

The different constraint types are as follows:

  • Doba platnosti
  • Povolené adresy UP
  • Povolené metody HTTP
  • Povolené referrery HTTP
Expiry time

Expiry time simply sets for how long you want your token to be usable, the default is 30 days. After the expiry time, the token will simply return a 401 (Unauthorized) message. You can set any expiry time you want, but it is strongly advised that you set an expiry time that is reasonable for your use case.

Allowed IP addresses

Toto je čárkami oddělený seznam IP adres, u kterých chcete omezit, odkud mohou pocházet požadavky na token.

Important: IP address validation relies on the X-Forwarded-For header, which can be spoofed. For security, make sure a load balancer or reverse proxy overwrites this header.

Allowed HTTP methods

A comma-separated list of HTTP methods you want your token to be able to use. If you only need your token to view data, not modify or delete, selecting only the GET HTTP method makes sense.

Allowed HTTP referrers

HTTP referer is a header added to the request, when you click on a link, this says which site/page you were on when you clicked the link. Read more about the HTTP referer header here: https://en.wikipedia.org/wiki/HTTP_referer

This can be used to limit the use of a "public" token embedded on another page on another site. Making sure that the referer header match the site hostname in should come from, can help avoid abuse of the token, e.g. if someone posts it on a public forum.

Important: this is not a security feature. The referer header can easily be spoofed. This setting is intended to discourage unauthorized third-party developers from connecting to public access instances.

Saving your token:

When you are done configuring your token, you can save it by clicking the "Generate new token" button, on the bottom right of the pop-up. When doing so the token will be saved and a secret token key will be generated on the server. The new secret token key will be shown on the bottom of the PAT token list with a green background, and the text "Newly created token". The secret token key will look similar to this:

d2pat_5xVA12xyUbWNedQxy4ohH77WlxRGVvZZ1151814092
Important: This generated secret token key will only be shown once, so it is important that you copy the token key now and save it in a secure place for use later. The secret token key will be securely hashed on the server, and only the hash of this secret token key will be saved to the database. This is done to minimize the security impact if someone gets unauthorized access to the database, similar to the way passwords are handled.

B. Creating a token via the API

Příklad, jak vytvořit nový osobní přístupový token pomocí API:

POST https://play.dhis2.org/dev/api/apiToken
Content-Type: application/json
Oprávnění: Základní správní obvod

{}
NB: Remember the empty JSON body ({}) in the payload!

To vrátí odpověď obsahující token podobný tomuto:

{
  "httpStatus": "Created",
  "httpStatusCode": 201,
  "status": "OK",
  "response": {
     "responseType": "ApiTokenCreationResponse",
     "key": "d2pat_5xVA12xyUbWNedQxy4ohH77WlxRGVvZZ1151814092",
     "uid": "jJYrtIVP7qU",
     "klass": "org.hisp.dhis.security.apikey.ApiToken",
     "errorReports": []
  }
}

Important: The token key will only be shown once here in this response. You need to copy and save this is in a secure place for use later!

Samotný token se skládá ze tří částí: 1. Prefix: (d2pat_) označuje, o jaký typ tokenu se jedná. 2. Náhodné bajty kódované Base64: (5xVA12xyUbWNedQxy4ohH77WlxRGVvZZ) 3. Kontrolní součet CRC32: (1151814092) část kontrolního součtu je doplněna 0, takže vždy zůstane deset znaků dlouhá.

Configure your token via the API:

Chcete-li změnit kterékoli z omezení vašeho tokenu, můžete zadat následující požadavek HTTP API.

NB: Only the constraints are possible to modify after the token is created!

PUT https://play.dhis2.org/dev/api/apiToken/jJYrtIVP7qU
Content-Type: application/json
Authorization: Basic admin district
{
  "version": 1,
  "type": "PERSONAL_ACCESS_TOKEN",
  "expire": 163465349603200,
  "attributes": [
      {
        "type": "IpAllowedList",
        "allowedIps": ["192.168.0.1"]
      },
      {
        "type": "MethodAllowedList",
        "allowedMethods": ["GET"]
      }
  ]
}

Using your Personal Access Token

To issue a request with your newly created token, use the Authorization header accordingly. The Authorization header format is:

Authorization: ApiToken [YOUR_SECRET_API_TOKEN_KEY]
Příklad:
GET https://play.dhis2.org/dev/api/apiToken/jJYrtIVP7qU
Content-Type: application/json
Authorization: ApiToken d2pat_5xVA12xyUbWNedQxy4ohH77WlxRGVvZZ1151814092

Deleting your Personal Access Token

You can delete your PATs either in the UI on your profile page where you created it, or via the API like this:

DELETE https://play.dhis2.org/dev/api/apiToken/jJYrtIVP7qU
Content-Type: application/json
Authorization: ApiToken d2pat_5xVA12xyUbWNedQxy4ohH77WlxRGVvZZ1151814092

OAuth2

DHIS2 supports the OAuth2 authentication protocol. OAuth2 is an open standard for authorization which allows third-party clients to connect on behalf of a DHIS2 user and get a reusable bearer token for subsequent requests to the Web API. DHIS2 does not support fine-grained OAuth2 roles but rather provides applications access based on user roles of the DHIS2 user.

Each client for which you want to allow OAuth 2 authentication must be registered in DHIS2. To add a new OAuth2 client go to Apps > Settings > OAuth2 Clients in the user interface, click Add new and enter the desired client name and the grant types.

Přidání klienta pomocí webového rozhraní API

An OAuth2 client can be added through the Web API. As an example, we can send a payload like this:

{
  "name": "OAuth2 Demo Client",
  "cid": "demo",
  "secret": "1e6db50c-0fee-11e5-98d0-3c15c2c6caf6",
  "grantTypes": [
    "password",
    "refresh_token",
    "authorization_code"
  ],
  "redirectUris": [
    "http://www.example.org"
  ]
}

Datový obsah lze odeslat pomocí následujícího příkazu:

SERVER="https://play.dhis2.org/dev"
curl -X POST -H "Content-Type: application/json" -d @client.json
  -u admin:district "$SERVER/api/oAuth2Clients"

Tohoto klienta použijeme jako základ pro naše další příklady udělení typů.

Udělení typu hesla

The simplest of all grant types is the password grant type. This grant type is similar to basic authentication in the sense that it requires the client to collect the user's username and password. As an example we can use our demo server:

SERVER="https://play.dhis2.org/dev"
SECRET="1e6db50c-0fee-11e5-98d0-3c15c2c6caf6"

curl -X POST -H "Accept: application/json" -u demo:$SECRET "$SERVER/uaa/oauth/token"
  -d grant_type=password -d username=admin -d password=district

Získáte tak podobnou odpověď:

{
  "expires_in": 43175,
  "scope": "ALL",
  "access_token": "07fc551c-806c-41a4-9a8c-10658bd15435",
  "refresh_token": "a4e4de45-4743-481d-9345-2cfe34732fcc",
  "token_type": "bearer"
}

For now, we will concentrate on the access_token, which is what we will use as our authentication (bearer) token. As an example, we will get all data elements using our token:

SERVER="https://play.dhis2.org/dev"
curl -H "Authorization: Bearer 07fc551c-806c-41a4-9a8c-10658bd15435" "$SERVER/api/33/dataElements.json"

Grant type refresh_token

In general the access tokens have limited validity. You can have a look at the expires_in property of the response in the previous example to understand when a token expires. To get a fresh access_token you can make another round trip to the server and use refresh_token which allows you to get an updated token without needing to ask for the user credentials one more time.

SERVER="https://play.dhis2.org/dev"
SECRET="1e6db50c-0fee-11e5-98d0-3c15c2c6caf6"
REFRESH_TOKEN="a4e4de45-4743-481d-9345-2cfe34732fcc"

curl -X POST -H "Accept: application/json" -u demo:$SECRET "$SERVER/uaa/oauth/token"
  -d "grant_type=refresh_token" -d "refresh_token=$REFRESH_TOKEN"

Odpověď bude přesně stejná, jako když dostanete token, kterým začnete.

Typ udělení authorization_code

Authorized code grant type is the recommended approach if you don't want to store the user credentials externally. It allows DHIS2 to collect the username/password directly from the user instead of the client collecting them and then authenticating on behalf of the user. Please be aware that this approach uses the redirectUris part of the client payload.

Step 1: Visit the following URL using a web browser. If you have more than one redirect URIs, you might want to add &redirect_uri=http://www.example.org to the URL:

SERVER="https://play.dhis2.org/dev"
$SERVER/uaa/oauth/authorize?client_id=demo&response_type=code

Step 2: After the user has successfully logged in and accepted your client access, it will redirect back to your redirect uri like this:

http://www.example.org/?code=XYZ

Step 3: This step is similar to what we did in the password grant type, using the given code, we will now ask for an access token:

SERVER="https://play.dhis2.org/dev"
SECRET="1e6db50c-0fee-11e5-98d0-3c15c2c6caf6"

curl -X POST -u demo:$SECRET -H "Accept: application/json" $SERVER/uaa/oauth/token
-d "grant_type=authorization_code" -d "code=XYZ"

Chybové a informační zprávy

The Web API uses a consistent format for all error/warning and informational messages:

{
  "httpStatus": "Forbidden",
  "message": "You don't have the proper permissions to read objects of this type.",
  "httpStatusCode": 403,
  "status": "ERROR"
}

Here we can see from the message that the user tried to access a resource I did not have access to. It uses the http status code 403, the HTTP status message forbidden and a descriptive message.

Tabulka: Vlastnosti WebMessage

Název Popis
httpStatus Zpráva o stavu HTTP pro tuto odpověď, další informace naleznete v RFC 2616 (část 10).
httpStatusCode Stavový kód HTTP pro tuto odpověď naleznete v dokumentu RFC 2616 (část 10), kde najdete další informace.
status DHIS2 status, possible values are OK | WARNING | ERROR, where OK means everything was successful, ERROR means that operation did not complete and WARNING means the operation was partially successful, if the message contains a response property, please look there for more information.
message Uživatelsky přívětivá zpráva informující o tom, zda byla operace úspěšná či nikoli.
devMessage Technickější a pro vývojáře přívětivější zpráva (v současnosti se nepoužívá).
Odezva Extension point for future extensions of the WebMessage format.

Formát data a období

Throughout the Web API, we refer to dates and periods. The date format is:

yyyy-MM-dd

For instance, if you want to express March 20, 2014, you must use 2014-03-20.

The period format is described in the following table (also available on the API endpoint /api/periodTypes)

Tabulka: Formát období

Časový úsek Formát Příklad Popis
Den yyyyMMdd 20040315 15. března 2004
Týden yyyyWn 2004W10 10. týden 2004
Týden středa yyyyWedWn 2015WedW5 5. týden s nástupem ve středu
Týden čtvrtek yyyyThuWn 2015ThuW6 6. týden se začátkem ve čtvrtek
Týden sobota yyyySatWn 2015SatW7 7. týden se začátkem v sobotu
Týden neděle yyyySunWn 2015SunW8 8. týden se začátkem neděle
Dvoutýdenní yyyyBiWn 2015BiW1 Týden 1-2 20015
Měsíc yyyyMM 200403 březen 2004
Dvouměsíční yyyyMMB 200401B leden–únor 2004
Čtvrtletí yyyyQn 2004Q1 leden–březen 2004
Šest měsíců yyyySn 2004S1 leden až červen 2004
Šestiměsíční duben yyyyAprilSn 2004AprilS1 duben-září 2004
Rok yyyy 2004 2004
Finanční rok duben yyyy duben 2004April duben 2004-březen 2005
Finanční rok červenec yyyyJuly 2004July Červenec 2004-červen 2005
Finanční rok říjen yyyyOct 2004 října Říjen 2004-září 2005

Relativní období

In some parts of the API, like for the analytics resource, you can utilize relative periods in addition to fixed periods (defined above). The relative periods are relative to the current date and allow e.g. for creating dynamic reports. The available relative period values are:

THIS_WEEK, LAST_WEEK, LAST_4_WEEKS, LAST_12_WEEKS, LAST_52_WEEKS,
THIS_BIWEEK, LAST_BIWEEK, LAST_4_BIWEEKS,
THIS_MONTH, LAST_MONTH, THIS_BIMONTH, LAST_BIMONTH, THIS_QUARTER, LAST_QUARTER,
THIS_SIX_MONTH, LAST_SIX_MONTH, MONTHS_THIS_YEAR, QUARTERS_THIS_YEAR,
THIS_YEAR, MONTHS_LAST_YEAR, QUARTERS_LAST_YEAR, LAST_YEAR, LAST_5_YEARS, LAST_10_YEARS, LAST_10_FINANCIAL_YEARS, LAST_12_MONTHS, 
LAST_3_MONTHS, LAST_6_BIMONTHS, LAST_4_QUARTERS, LAST_2_SIXMONTHS, THIS_FINANCIAL_YEAR,
LAST_FINANCIAL_YEAR, LAST_5_FINANCIAL_YEARS

Vlastní období data

Zdroje query Analytiky podporují další parametry pro vyjádření období.

Default pe dimension will fall back to:

  • eventDate pro /analytics/events/query
  • denrollmentDate pro /analytics/enrollments/query

Adding conditions on one or more date fields and combining them are allowed.

Usage of custom date periods

Ve zdrojích podporujících vlastní období data jsou další parametry dotazu, které budou zkombinovány za účelem vyjádření podmínek v časové dimenzi.

vlastní datum období zdroj dotazu na události zdroj dotazu na zápis
eventDate [x] [ ]
enrollmentDate [x] [x]
scheduledDate [x] [ ]
incidentDate [x] [x]
lastUpdated [x] [x]

Podmínky mohou být vyjádřeny v následující formě:

analytics/events/query/...?...&eventDate=2021&...

V jednom dotazu je možné kombinovat více časových polí:

analytics/events/query/...?...&eventDate=2021&incidentDate=202102&...

Všechny tyto podmínky lze kombinovat s dimenzí pe:

analytics/events/query/...?...&dimension=pe:TODAY&enrollmentDate=2021&incidentDate=202102&...

Podporované formáty jsou popsány výše v části „Formát data a období“. K dispozici je další formát pro vyjádření rozsahu dat: yyyyMMdd_yyyyMMdd a yyyy-MM-dd_yyyy-MM-dd.

V níže uvedeném příkladu bude koncový bod vracet události, které se mají uskutečnit mezi 20210101 a 20210104:

analytics/events/query/...?...&dimension=pe:TODAY&enrollmentDate=2021&incidentDate=202102&scheduledDate=20210101_20210104&...

Authorities

ID a názvy systémových autorit lze vypsat pomocí:

/api/authorities

Vrací následující formát:

{
  "systemAuthorities": [
    {
      "id": "ALL",
      "name": "ALL"
    },
    {
      "id": "F_ACCEPT_DATA_LOWER_LEVELS",
      "name": "Accept data at lower levels"
    }
  ]
}