Skip to content

Stac fastapi

AuthenticationFlow

Bases: BaseModel

STAC authentication model.

Parameters:

Name Type Description Default
flow Literal['client_credentials', 'authorization_code']

Flow to use.

required
token_url str

Token URL for authentication server.

required
client_id str

Client id.

required
client_secret str

Client secret.

required
kwargs dict[str, Any]

Extra kwargs for Authentication.

{}
Source code in stac_generator/plugins/outputs/stac_fastapi.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class AuthenticationFlow(BaseModel):
    """STAC authentication model."""

    flow: Literal["client_credentials", "authorization_code"] = Field(
        description="Flow to use.",
    )
    token_url: str = Field(
        description="Token URL for authentication server.",
    )
    client_id: str = Field(
        description="Client id.",
    )
    client_secret: str = Field(
        description="Client secret.",
    )
    kwargs: dict[str, Any] = Field(
        default={},
        description="Extra kwargs for Authentication.",
    )

AuthorizationCode

Bases: AuthenticationFlow

STAC Authorization Code model.

Parameters:

Name Type Description Default
flow Literal['authorization_code']

Flow to use.

required
authorization_url str

Token URL for authentication server.

required
Source code in stac_generator/plugins/outputs/stac_fastapi.py
50
51
52
53
54
55
56
57
58
class AuthorizationCode(AuthenticationFlow):
    """STAC Authorization Code model."""

    flow: Literal["authorization_code"] = Field(
        description="Flow to use.",
    )
    authorization_url: str = Field(
        description="Token URL for authentication server.",
    )

ClientCredentials

Bases: AuthenticationFlow

STAC Client Credentials model.

Parameters:

Name Type Description Default
flow Literal['client_credentials']

Flow to use.

required
Source code in stac_generator/plugins/outputs/stac_fastapi.py
42
43
44
45
46
47
class ClientCredentials(AuthenticationFlow):
    """STAC Client Credentials model."""

    flow: Literal["client_credentials"] = Field(
        description="Flow to use.",
    )

STACFastAPIConf

Bases: BaseModel

STAC FastAPI config model.

Parameters:

Name Type Description Default
api_url str

URL for API.

required
authentication AuthorizationCode | ClientCredentials

Authentication for STAC API.

None
headers dict

Headers for API request.

{}
verify bool

API certificate verifcation.

False
Source code in stac_generator/plugins/outputs/stac_fastapi.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class STACFastAPIConf(BaseModel):
    """STAC FastAPI config model."""

    api_url: str = Field(
        description="URL for API.",
    )
    authentication: AuthorizationCode | ClientCredentials = Field(
        default=None,
        description="Authentication for STAC API.",
    )
    headers: dict = Field(
        default={},
        description="Headers for API request.",
    )
    verify: bool = Field(
        default=False,
        description="API certificate verifcation.",
    )

STACFastAPIOutput

Bases: Output

Output to a STAC FastAPI using the Transaction endpoint extension

Plugin name: stac_fastapi

Example Configuration

.. code-block:: yaml

- name: stac_fastapi
  conf:
    api_url: https://localhost
Source code in stac_generator/plugins/outputs/stac_fastapi.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
class STACFastAPIOutput(Output):
    """
    Output to a STAC FastAPI using the Transaction endpoint extension

    **Plugin name:** ``stac_fastapi``

    Example Configuration:
        .. code-block:: yaml

            - name: stac_fastapi
              conf:
                api_url: https://localhost
    """

    config_class = STACFastAPIConf

    def item(
        self,
        data: dict,
        client: Client,
        auth: OAuth2AuthorizationCodePKCE | OAuth2ClientCredentials | None,
    ) -> None:

        collection = data["collection"]

        response = client.post(
            urljoin(self.conf.api_url, f"collections/{collection}/items"),
            json=data,
            auth=auth,
            headers=self.conf.headers,
        )

        if response.status_code == 404:

            response_json = response.json()

            if response_json["description"] == f"Collection {collection} does not exist":
                collection_data = {
                    "type": "Collection",
                    "id": collection,
                    "description": collection,
                    "stac_version": "0.1.0",
                    "stac_extensions": [],
                    "license": data.get("license", "other"),
                    "extent": {
                        "spatial": {"bbox": [[-180, -90, 180, 90]]},
                        "temporal": {
                            "interval": [["1992-01-01T00:00:00Z", "2015-12-31T00:00:00Z"]]
                        },
                    },
                    "links": data.get("links", [])
                    + [
                        {
                            "rel": "self",
                            "type": "application/geo+json",
                            "href": f"{self.conf.api_url}/collections/{collection}",
                        },
                        {
                            "rel": "parent",
                            "type": "application/json",
                            "href": f"{self.conf.api_url}/",
                        },
                        {
                            "rel": "queryables",
                            "type": "application/json",
                            "href": f"{self.conf.api_url}/collections/{collection}/queryables",
                        },
                        {
                            "rel": "items",
                            "type": "application/geo+json",
                            "href": f"{self.conf.api_url}/collections/cmip6/{collection}",
                        },
                        {
                            "rel": "root",
                            "type": "application/json",
                            "href": self.conf.api_url,
                        },
                    ],
                }

                response = client.post(
                    urljoin(self.conf.api_url, "collections"),
                    json=collection_data,
                    auth=auth,
                    headers=self.conf.headers,
                )

                response = client.post(
                    urljoin(self.conf.api_url, f"collections/{collection}/items"),
                    json=data,
                    auth=auth,
                    headers=self.conf.headers,
                )

        if response.status_code == 409:
            response_json = response.json()

            if (
                response_json["description"]
                == f"Item {data['id']} in collection {collection} already exists"
            ):
                response = client.put(
                    urljoin(self.conf.api_url, f"collections/{collection}/items/{data['id']}"),
                    json=data,
                    auth=auth,
                )

                if response.is_error:
                    print(
                        f"FastAPI Output Item update failed with status code: {response.status_code} and response text: {response.text}",
                    )

        elif response.is_error:
            print(
                f"FastAPI Output failed to post to STAC Fastapi items endpoint returned status code: {response.status_code} and response text: {response.text} request data: {data}",
            )

    def collection(self, data: dict, client: Client, auth: OAuth2ClientCredentials | None) -> None:
        response = client.post(urljoin(self.conf.api_url, "collections"), json=data, auth=auth)

        if response.status_code == 409:
            response_json = response.json()

            if response_json["description"] == f"Collection {data['id']} already exists":
                response = client.put(
                    urljoin(self.conf.api_url, "collections"),
                    # urljoin(self.api_url, f"collections/{data['id']}"),
                    json=data,
                    auth=auth,
                )

                if response.is_error:
                    LOGGER.warning(
                        "FastAPI Output Collection update failed with status code: %s and response text: %s",
                        response.status_code,
                        response.text,
                    )

        elif response.is_error:
            LOGGER.warning(
                "FastAPI Output failed to post to STAC Fastapi collections endpoint returned status code: %s and response text: %s request data: %s",
                response.status_code,
                response.text,
                data,
            )

    def export(self, data: dict, **kwargs) -> None:
        client = Client(
            verify=self.conf.verify,
            timeout=180,
        )

        auth = None
        match self.conf.authentication:

            case ClientCredentials():
                auth = OAuth2ClientCredentials(
                    token_url=self.conf.authentication.token_url,
                    client_id=self.conf.authentication.client_id,
                    client_secret=self.conf.authentication.client_secret,
                    **self.conf.authentication.kwargs,
                )

            case AuthorizationCode():
                auth = OAuth2AuthorizationCodePKCE(
                    authorization_url=self.conf.authentication.authorization_url,
                    token_url=self.conf.authentication.token_url,
                    client_id=self.conf.authentication.client_id,
                    client_secret=self.conf.authentication.client_secret,
                    **self.conf.authentication.kwargs,
                )

        if kwargs["GENERATOR_TYPE"] == "item":
            self.item(data, client, auth)

        elif kwargs["GENERATOR_TYPE"] == "collection":
            self.collection(data, client, auth)