DICOMweb client
How to search, retrieve and store over HTTP with
dicomweb.Client
and the qido, wado and stow commands: the QIDO-RS, WADO-RS and STOW-RS
services of PS3.18. For a server see DICOMweb server.
Overview
| Service | Request | Go | Command |
|---|---|---|---|
| QIDO‑RS | GET /studies?..., /series, /instances | SearchForStudies, SearchForSeries, SearchForInstances, SearchEach | go-dicom qido |
| WADO‑RS | GET /studies/{study}[/series/{series}[/instances/{instance}]] | RetrieveStudy, RetrieveSeries, RetrieveInstance, RetrieveEach, RetrieveStream | go-dicom wado |
| WADO‑RS metadata | .../metadata | RetrieveMetadata, RetrieveMetadataWithBulkData | go-dicom wado -metadata |
| WADO‑RS frames, rendered, thumbnail, bulk data | .../frames/{list}, .../rendered, .../thumbnail, a BulkDataURI | RetrieveFrames, RetrieveRendered, RetrieveThumbnail, RetrieveBulkData | |
| STOW‑RS | POST /studies[/{study}] | Store, StoreDatasets, StoreStream | go-dicom stow |
The examples were run against qrscp -web on this machine
(http://127.0.0.1:41080/dicom-web), holding pydicom's CT_small.dcm and
MR_small.dcm.
Making a client
client, err := dicomweb.NewClient("http://127.0.0.1:41080/dicom-web",
dicomweb.WithBearerToken(os.Getenv("DICOMWEB_TOKEN")))
if err != nil {
return err
}The URL is the service root, under which studies lives. Options:
| Option | Effect |
|---|---|
WithBearerToken(token) | Authorization: Bearer ... on every request |
WithBasicAuth(user, password) | HTTP Basic credentials |
WithHeader(name, value) | Any other header, on every request |
WithHTTPClient(c) | Your *http.Client: its transport carries TLS, proxies and timeouts. See TLS and security. |
WithMaxResponseBytes(n) | The most bytes of one response; past it the call fails. Default 4 GiB (DefaultMaxResponseBytes). |
WithRetrieveTransferSyntax(uid) | The transfer syntax WADO‑RS asks instances in; default *, each as stored |
Without WithHTTPClient, a request has no overall time limit, since
retrieving a study may take long; the context of each call stops it, and
waiting for the server to start answering is limited to a minute. A Client
is safe for use by several goroutines.
Searching (QIDO-RS)
studies, err := client.SearchForStudies(ctx, dicomweb.Query{
Match: map[string]string{"PatientName": "CompressedSamples*", "StudyDate": "20040101-20041231"},
IncludeFields: []string{"StudyDescription"},
Limit: 20,
})
if err != nil {
return err
}
for _, s := range studies {
fmt.Println(s.GetStringByKeyword("PatientName"), s.GetStringByKeyword("StudyInstanceUID"))
}Query
names attributes by keyword or by eight hex digits ("00100010"), with a
single value, a wildcard, a range or a list. IncludeFields asks for more
attributes (or "all"), Limit and Offset page, and FuzzyMatching asks
for fuzzy name matching, which a server may not offer. Each result is a
*dataset.Dataset, as a C-FIND match is. A response with no match (204) is
an empty slice.
SearchEach hands each match over as it is decoded, so a search of a hundred
thousand matches is read in the memory of one, and bounds each match instead
of the whole response:
n := 0
err = client.SearchEach(ctx, dicomweb.SearchInstances, study, "", dicomweb.Query{},
1<<20, // no match's DICOM JSON may pass 1 MiB
func(ds *dataset.Dataset) error {
n++
return nil
})
if errors.Is(err, dicomweb.ErrMatchTooLarge) {
return fmt.Errorf("a match was larger than the bound: %w", err)
}
if err != nil {
return err
}The levels are SearchStudies, SearchSeries and SearchInstances; the
study and series UIDs narrow the resource as in the SearchFor methods.
$ go-dicom qido -match "PatientName=CompressedSamples*" http://127.0.0.1:41080/dicom-web
--- Result 1 ---
(0008,0020) DA Study Date 20040119
(0008,0030) TM Study Time 072730
(0008,0056) CS Instance Availability ONLINE
(0008,0061) CS Modalities in Study CT
(0008,0201) SH Timezone Offset From UTC -0500
(0008,1190) UR Retrieve URL http://127.0.0.1:41080/dicom-web/studies/1.3.6.1.4.1.5962.1.2.1.20040119072730.12322
(0010,0010) PN Patient's Name CompressedSamples^CT1
(0010,0020) LO Patient ID 1CT1
...
Found 2 result(s)
$ go-dicom qido -level series -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 http://127.0.0.1:41080/dicom-web
$ go-dicom qido -level instance -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 -json http://127.0.0.1:41080/dicom-webqido takes -level, -study, -series, -match (repeatable),
-include, -limit, -offset, -fuzzy and -json.
Retrieving (WADO-RS)
RetrieveStudy, RetrieveSeries and RetrieveInstance return data sets,
the whole response held in memory. RetrieveEach hands each instance over
as it arrives, as the Part 10 file the server sent:
err = client.RetrieveEach(ctx, study, "", "", func(p dicomweb.Part) error {
ds, err := p.Dataset()
if err != nil {
return err
}
name := filepath.Join(dir, ds.GetStringByKeyword("SOPInstanceUID")+".dcm") // check the UID before trusting it as a name
return os.WriteFile(name, p.Data, 0o644)
})RetrieveStream gives each part as a reader, so an instance larger than
memory is written as it arrives, and bounds each part:
err = client.RetrieveStream(ctx, study, "", "", 4<<30, func(p dicomweb.StreamPart) error {
f, err := os.CreateTemp(dir, "*.dcm")
if err != nil {
return err
}
_, err = io.Copy(f, p.Data)
if closeErr := f.Close(); err == nil {
err = closeErr
}
return err
})A part past the bound ends the retrieval with a *PartTooLargeError, which
errors.Is(err, dicomweb.ErrPartTooLarge) matches. p.MediaType and
p.TransferSyntax say what the part is (application/dicom,
1.2.840.10008.1.2.1 here).
RetrieveMetadata returns the instances without their bulk data, which is
how a study is examined without downloading it; each left-out value is named
by a BulkDataURI. RetrieveMetadataWithBulkData fetches each of those and
puts it in its element, so each data set is the instance whole, Pixel Data
uncompressed. RetrieveBulkData(ctx, uri) fetches one.
$ go-dicom wado -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 http://127.0.0.1:41080/dicom-web wado-out
wado-out/1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322.dcm
Retrieved 1 instance(s) to wado-out
$ go-dicom wado -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 -transfer-syntax 1.2.840.10008.1.2.4.80 http://127.0.0.1:41080/dicom-web wado-jls
wado-jls/1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322.dcm
Retrieved 1 instance(s) to wado-jls
$ go-dicom wado -study 1.3.6.1.4.1.5962.1.2.1.20040119072730.12322 -metadata http://127.0.0.1:41080/dicom-web > study.jsonWithout -transfer-syntax, each instance comes as the server holds it; the
file wado-out received is byte for byte the one in the archive. A server
may refuse a syntax: asked for JPEG Baseline, qrscp answered
406 Not Acceptable: ... it is lossy, and a lossy copy is a new instance, which needs a new SOP Instance UID that a retrieve does not assign.
Frames, rendered pictures and thumbnails
frames, err := client.RetrieveFrames(ctx, study, series, instance, []int{1}, dicomweb.FrameOptions{})
if err != nil {
return err
}
fmt.Println("frame:", len(frames[0].Data), "bytes,", frames[0].MediaType, frames[0].TransferSyntax)
asJLS, err := client.RetrieveFrames(ctx, study, series, instance, []int{1},
dicomweb.FrameOptions{MediaType: "image/jls"})
if err != nil {
return err
}Printed: frame: 32768 bytes, application/octet-stream 1.2.840.10008.1.2.1,
then the same frame as image/jls in 1.2.840.10008.1.2.4.80, 14146 bytes.
Frames are numbered from 1 and come back in the order asked. FrameOptions
asks for them uncompressed (the default), as stored (TransferSyntax: "*"),
or in a compressed type (image/jpeg, image/jls, image/jp2,
image/jphc, image/dicom-rle). A frame the instance does not have is the
server's 404.
pics, err := client.RetrieveRendered(ctx, study, series, instance, nil, dicomweb.RenderedOptions{
MediaType: "image/png",
Window: &dataset.Window{Center: 40, Width: 400},
Viewport: &dicomweb.Viewport{Width: 256, Height: 256},
})
if err != nil {
return err
}
thumb, err := client.RetrieveThumbnail(ctx, study, "", "", nil, dicomweb.RenderedOptions{})RenderedOptions
sets the media type (JPEG by default), quality, window, viewport, ICC profile
and annotation; a thumbnail sends only the media type and viewport. Each
picture is a
MediaPart
with its bytes and media type.
Storing (STOW-RS)
ct, err := os.ReadFile("study/ct.dcm")
if err != nil {
return err
}
result, err := client.Store(ctx, "", ct)
if result != nil {
for _, f := range result.Failed {
fmt.Printf("refused %s: %04X\n", f.SOPInstanceUID, f.FailureReason)
}
}
if err != nil {
return err // a *StatusError when the server refused any; result says which
}
fmt.Println("stored", len(result.Stored))- The second argument is a study UID, empty to store to
/studies. A server refuses an instance of another study (A900 fromqrscp). - A
202(some kept) is not an error.Failedsays which were not, each with its failure reason;Storedlists the rest, with aWarningReasonwhen the server changed one. - A
409or400is a*StatusError, returned together with the result whenever the server gave its account of each instance. StoreDatasetssends data sets, each written as a Part 10 file in the syntax it holds.
StoreStream sends instances that are not in memory. It writes the body
through a pipe as it reads each reader, chunked, with no Content-Length:
paths := []string{"study/ct.dcm", "study/mr.dcm"}
next := 0
result, err = client.StoreStream(ctx, "", func() (io.Reader, error) {
if next == len(paths) {
return nil, io.EOF
}
f, err := os.Open(paths[next]) // closed by StoreStream once read
next++
return f, err
})
if err != nil {
return err
}An error from the function or a reader ends the body without its closing boundary, so the server never takes it for a whole request.
$ go-dicom stow http://127.0.0.1:41080/dicom-web stowdir/
Stored 2 instance(s)
$ go-dicom stow -study 1.2.3.4 http://127.0.0.1:41080/dicom-web study/ct.dcm
refused 1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322: the data set does not match its SOP class (A900H)
Stored 0 instance(s), 1 refused
Error: stow: the server refused 1 instance(s)stow walks directories, passes over what is not DICOM, sends files as they
are in requests of up to 100 files or 64 MiB, and fails if any instance was
refused.
Errors
| Error | Means | Check with |
|---|---|---|
*StatusError | A status the request did not want; StatusCode, URL (without the query), and the start of the server's Body | errors.As |
*ResponseTooLargeError | The response passed WithMaxResponseBytes | errors.Is(err, dicomweb.ErrResponseTooLarge) |
*PartTooLargeError | A part passed RetrieveStream's bound | errors.Is(err, dicomweb.ErrPartTooLarge) |
*MatchTooLargeError | A match passed SearchEach's bound | errors.Is(err, dicomweb.ErrMatchTooLarge) |
_, err = client.RetrieveMetadata(ctx, "1.2.3.999", "", "")
var status *dicomweb.StatusError
if errors.As(err, &status) {
fmt.Println("server said", status.StatusCode, status.Body)
}printed server said 404 the archive holds no such instances.
The command line
qido, wado and stow share these flags:
| Flag | Meaning | In Go |
|---|---|---|
-token (or DICOMWEB_TOKEN) | Bearer token | WithBearerToken |
-user user:pass | Basic credentials | WithBasicAuth |
-header 'N: v' | Any header, repeatable | WithHeader |
-tls-ca file | CAs to verify the server against | WithHTTPClient with RootCAs |
-tls-insecure | No verification (testing only) | WithHTTPClient with InsecureSkipVerify |
-timeout seconds | Give up after this long | the context, or the client's Timeout |
Tip
Set the token in DICOMWEB_TOKEN rather than with -token: an option is
readable in the process list.
Limits and gotchas
- XML responses, UPS-RS and the capabilities service are not implemented.
- A BulkDataURI on another scheme, host or port than the service is refused before any request, so the client's credentials go nowhere else.
RetrieveStudyand its siblings hold the whole response, up to the response bound; useRetrieveEachorRetrieveStreamfor large studies.stowprints A900 as "does not match its SOP class"; fromqrscpit means the instance is not of the study named in the request.- CONFORMANCE.md §4.1 states what is and is not supported, and what it was checked against.
See also
- DICOMweb server
- TLS and security
- Query/retrieve and worklist for the matching rules a search uses on a go-dicom server
dicomwebon pkg.go.dev