Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
Python Packaging User Guide
Python Packaging User Guide
Back to top

Simple repository API

The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”,“SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”,and “OPTIONAL”” in this document are to be interpreted as described inRFC 2119.

The interface for querying available package versions andretrieving packages from an index server comes in two forms:HTML andJSON.

Base API

A repository that implements the simple API is defined by its base URL. This isthe top level URL that all additional URLs are below. The API is named the“simple” repository due to the fact that PyPI’s base URL ishttps://pypi.org/simple/.

Note

All subsequent URLs in this document will be relative to this baseURL (so given PyPI’s URL, a URL of/foo/ would behttps://pypi.org/simple/foo/.

Normalized Names

This spec references the concept of a “normalized” project name. As perthe name normalization specificationthe only valid characters in a name are the ASCII alphabet, ASCII numbers,.,-, and_. The name should be lowercased with all runs of thecharacters.,-, or_ replaced with a single- character. Thiscan be implemented in Python with there module:

importredefnormalize(name):returnre.sub(r"[-_.]+","-",name).lower()

Versioning PyPI’s Simple API

This spec proposes the inclusion of a meta tag on the responses of everysuccessful request to a simple API page, which contains a name attributeofpypi:repository-version, and a content that is aversion specifiersspecification compatibleversion number, which is further constrained to ONLY be Major.Minor, andnone of the additional features supported bythe version specifiersspecification.

This would end up looking like:

<metaname="pypi:repository-version"content="1.4">

When interpreting the repository version:

  • Incrementing the major version is used to signal a backwardsincompatible change such that existing clients would no longer beexpected to be able to meaningfully use the API.

  • Incrementing the minor version is used to signal a backwardscompatible change such that existing clients would still beexpected to be able to meaningfully use the API.

It is left up to the discretion of any future specs as to whatspecifically constitutes a backwards incompatible vs compatible changebeyond the broad suggestion that existing clients will be able to“meaningfully” continue to use the API, and can include adding,modifying, or removing existing features.

It is expectation of this spec that the major version will never beincremented, and any future major API evolutions would utilize adifferent mechanism for API evolution. However the major versionis included to disambiguate with future versions (e.g. a hypotheticalsimple api v2 that lived at /v2/, but which would be confusing if therepository-version was set to a version >= 2).

API Version History

This section contains only an abbreviated history of changes,as marked by the API version number. For a full history of changes includingchanges made before API versioning, seeHistory.

  • API version 1.0: Initial version of the API, declared withPEP 629.

  • API version 1.1: Addedversions,files[].size, andfiles[].upload-time metadatato the JSON serialization, declared withPEP 700.

  • API version 1.2: Added repository “tracks” metadata, declared withPEP 708.

  • API version 1.3: Added provenance metadata, declared withPEP 740.

  • API version 1.4: Added status markers, declared withPEP 792.

Clients

Clients interacting with the simple APISHOULD introspect eachresponse for the repository version, and if that data does not existMUST assume that it is version 1.0.

When encountering a major version greater than expected, clientsMUST hard fail with an appropriate error message for the user.

When encountering a minor version greater than expected, clientsSHOULD warn users with an appropriate message.

ClientsMAY still continue to use feature detection in order todetermine what features a repository uses.

HTML Serialization

The following constraints apply to all HTML serialized responses described inthis spec:

  • All HTML responsesMUST be a valid HTML5 document.

  • HTML responsesMAY contain one or moremeta tags in the<head> section. The semantics of these tags are defined below.

Project List

Within a repository, the root URL (/ for this spec which represents the baseURL)MUST be a valid HTML5 page with a single anchor element per project inthe repository.

The text of each anchor tagMUST be the name ofthe project and thehref attributeMUST link to the URL for that particularproject. As an example:

<!DOCTYPE html><html><body><ahref="/frob/">frob</a><ahref="/spamspamspam/">spamspamspam</a></body></html>

Project Detail

Below the root URL is another URL for each individual project contained withina repository. The format of this URL is/<project>/, where the<project>is replaced by the normalized name for that project.

Tip

For example, a project named “HolyGrail” would have a URL like/holygrail/.

The project detail URL must respond with a valid HTML5 page with a singleanchor element per file for the project. Thehref attributeMUST be aURL that links to the location of the file for download, and the text of theanchor tagMUST match the final path component (the filename) of the URL.

Each file URLSHOULD include a hash in theform of a URL fragment with the following syntax:#<hashname>=<hashvalue>,where<hashname> is the lowercase name of the hash function (such assha256) and<hashvalue> is the hex encoded digest.

In addition to the above, the following constraints are placed on the API:

  • All URLs which respond with an HTML5 pageMUST end with a/ and therepositorySHOULD redirect the URLs without a/ to add a/ to theend.

  • URLs may be either absolute or relative as long as they point to the correctlocation.

  • There are no constraints on where the files must be hosted relative to therepository.

  • There may be any other HTML elements on the API pages as long as the requiredanchor elements exist.

  • RepositoriesMAY redirect unnormalized URLs to the canonical normalizedURL (e.g./Foobar/ may redirect to/foobar/), however clientsMUST NOT rely on this redirection andMUST request the normalizedURL.

  • RepositoriesSHOULD choose a hash function from one of the onesguaranteed to be available via thehashlib module in the Python standardlibrary (currentlymd5,sha1,sha224,sha256,sha384,sha512). The current recommendation is to usesha256.

  • If there is a GPG signature for a particular distribution file itMUSTlive alongside that file with the same name with a.asc appended to it.So if the file/packages/HolyGrail-1.0.tar.gz existed and had anassociated signature, the signature would be located at/packages/HolyGrail-1.0.tar.gz.asc.

  • A repositoryMAY include adata-core-metadata attribute on a filelink.

    The repositorySHOULD provide the hash of the Core Metadata file as thedata-core-metadata attribute’s value using the syntax<hashname>=<hashvalue>, where<hashname> is the lower cased name ofthe hash function used, and<hashvalue> is the hex encoded digest. TherepositoryMAY usetrue as the attribute’s value if a hash is unavailable.

  • A repositoryMAY include adata-dist-info-metadata attribute on afile link.

    Index clientsMAY consume this key if present, as a legacy fallbackfordata-core-metadata.

    Important

    data-dist-info-metadata was standardized withPEP 658 and renamed todata-core-metadata withPEP 714.

  • A repositoryMAY include adata-gpg-sig attribute on a file link witha value of eithertrue orfalse to indicate whether or not there is aGPG signature. Repositories that do thisSHOULD include it on every link.

  • A repositoryMAY include adata-requires-python attribute on a filelink. This exposes theRequires-Python metadata fieldfor the corresponding release. Where this is present, installer toolsSHOULD ignore the download when installing to a Python version thatdoesn’t satisfy the requirement. For example:

    <ahref="..."data-requires-python="&gt;=3">...</a>

    In the attribute value, < and > have to be HTML encoded as&lt; and&gt;, respectively.

  • A repositoryMAY include adata-yanked attribute on a file link.

    Thedata-yanked attribute may have no value, or may have anarbitrary string as a value. The presence of adata-yanked attributeSHOULD be interpreted as indicating that the file pointed to by thisparticular link has been “Yanked”, and should not generally be selected byan installer, except under specific scenarios.

    The value of thedata-yanked attribute, if present, is an arbitrarystring that represents the reason for why the file has been yanked.

    Note

    The semantics of how tools should handle yanked files isdescribed inFile Yanking.

  • A repositoryMAY include adata-provenance attribute on a file link.The value of this attributeMUST be a fully qualified URL, signaling thatthe file’s provenance can be found at that URL. This URLMUST representasecure origin.

    Note

    Thedata-provenance attribute was added with API version 1.3.

    Note

    The format of the linked provenance is defined inIndex hosted attestations.

  • A repositoryMAY includepypi:project-status andpypi:project-status-reason meta tags on the response itself.

    The value ofpypi:project-statusMUST be a validproject status marker, while the value ofpypi:project-status-reasonMUST be an arbitrary string if present.

    Note

    The set of valid project status markers and their semantics is describedinProject Status Markers.

    Note

    Thepypi:project-status andpypi:project-status-reason meta tagswere added with API version 1.4.

Serve Distribution Metadata in the Simple Repository API

In a simple repository’s project page, each anchor tag pointing to adistributionMAY have adata-dist-info-metadata attribute. Thepresence of the attribute indicates the distribution represented bythe anchor tagMUST contain a Core Metadata file that will not bemodified when the distribution is processed and/or installed.

If adata-dist-info-metadata attribute is present, the repositoryMUST serve the distribution’s Core Metadata file alongside thedistribution with a.metadata appended to the distribution’s filename. For example, the Core Metadata of a distribution served at/files/distribution-1.0-py3.none.any.whl would be located at/files/distribution-1.0-py3.none.any.whl.metadata. This is similarto howthe base HTML API specificationspecifies the GPG signature file’s location.

The repositorySHOULD provide the hash of the Core Metadata fileas thedata-dist-info-metadata attribute’s value using the syntax<hashname>=<hashvalue>, where<hashname> is the lower casedname of the hash function used, and<hashvalue> is the hex encodeddigest. The repositoryMAY usetrue as the attribute’s valueif a hash is unavailable.

Backwards Compatibility

If an anchor tag lacks thedata-dist-info-metadata attribute,tools are expected to revert to their current behaviour of downloadingthe distribution to inspect the metadata.

Older tools not supporting the newdata-dist-info-metadataattribute are expected to ignore the attribute and maintain theircurrent behaviour of downloading the distribution to inspect themetadata. This is similar to how priordata- attribute additionsexpect existing tools to operate.

JSON-based Simple API for Python Package Indexes

To enable response parsing with only the standard library, this spec specifies thatall responses (besides the files themselves, and the HTML responses fromthe base HTML API specification) should beserialized usingJSON.

To enable zero configuration discovery and to minimize the amount of additional HTTPrequests, this spec extendsthe base HTML API specification such that all of the API endpoints (other than thefiles themselves) will utilize HTTP content negotiation to allow client and server toselect the correct serialization format to serve, i.e. either HTML or JSON.

Versioning

Versioning will adhere tothe API versioning specification format (Major.Minor), which has defined theexisting HTML responses to be1.0. Since this spec does not introduce new featuresinto the API, rather it describes a different serialization format for the existingfeatures, this spec does not change the existing1.0 version, and instead justdescribes how to serialize that into JSON.

Similar tothe API versioning specification, the major version numberMUST beincremented if anychanges to the new format would result in no longer being able to expect existingclients to meaningfully understand the format.

Likewise, the minor versionMUST be incremented if features areadded or removed from the format, but existing clients would be expected to continueto meaningfully understand the format.

Changes that would not result in existing clients being unable to meaningfullyunderstand the format and which do not represent features being added or removedmay occur without changing the version number.

This is intentionally vague, as this spec believes it is best left up to future specsthat make any changes to the API to investigate and decide whether or not thatchange should increment the major or minor version.

Future versions of the API may add things that can only be represented in a subsetof the available serializations of that version. All serializations version numbers,within a major version,SHOULD be kept in sync, but the specifics of how afeature serializes into each format may differ, including whether or not that featureis present at all.

It is the intent of this spec that the API should be thought of as URL endpoints thatreturn data, whose interpretation is defined by the version of that data, and thenserialized into the target serialization format.

JSON Serialization

The URL structure fromthe base HTML API specification still applies, as this spec only addsan additional serialization format for the already existing API.

The following constraints apply to all JSON serialized responses described in thisspec:

  • All JSON responses willalways be a JSON object rather than an array or othertype.

  • While JSON doesn’t natively support a URL type, any value that represents anURL in this API may be either absolute or relative as long as they point tothe correct location. If relative, they are relative to the current URL as ifit were HTML.

  • Additional keys may be added to any dictionary objects in the API responsesand clientsMUST ignore keys that they don’t understand.

  • All JSON responses will have ameta key, which contains information related tothe response itself, rather than the content of the response.

  • All JSON responses will have ameta.api-version key, which will be a string thatcontains theAPI versioning specificationMajor.Minor version number, with thesame fail/warn semantics as defined inthe API versioning specification.

  • All requirements ofthe base HTML API specification that are not HTML specific still apply.

  • Keys (at any level) with a leading underscore are reserved as private forindex server use. No future standard will assign a meaning to any such key.

Project List

The root URL/ for this spec (which represents the base URL) will be a JSON encodeddictionary which has a two keys:

  • projects: An array where each entry is a dictionary with a single key,name, which represents string of the project name.

  • meta: The general response metadata asdescribed earlier.

As an example:

{"meta":{"api-version":"1.4"},"projects":[{"name":"Frob"},{"name":"spamspamspam"}]}

Note

Thename field is the same as the one fromthe base HTML APIspecification, which does not specifywhether it is the non-normalized display name or the normalized name. In practicedifferent implementations of these specs are choosing differently here, so relyingon it being either non-normalized or normalized is relying on an implementationdetail of the repository in question.

Note

While theprojects key is an array, and thus is required to be in some kindof an order, neitherthe base HTML API specification nor this spec requires any specific ordering northat the ordering is consistent from one request to the next. Mentally this isbest thought of as a set, but both JSON and HTML lack the functionality to havesets.

Project Detail

The format of this URL is/<project>/ where the<project> is replaced by thethe base HTML API specification normalizedname for that project, so a project named “Silly_Walk” wouldhave a URL like/silly-walk/.

This URL must respond with a JSON encoded dictionary that has four keys:

  • name: The normalized name of the project.

  • files: A list of dictionaries, each one representing an individual file.

  • meta: The general response metadata asdescribed earlier.

    In addition to the general response metadata, the project detailmetadictionaryMAY also include the following:

    • project-status: If present, thisMUST be a valid project status marker.

      Note

      The set of valid project status markers and their semantics is describedinProject Status Markers.

      Note

      Theproject-status key was added with API version 1.4.

    • project-status-reason: If present, thisMUST be an arbitrary stringdescription of the project status.

      Note

      Theproject-status-reason key was added with API version 1.4.

  • versions: A list of version strings specifying all of the project versionsuploaded for this project. The value ofversions is logically a set,and as such may not contain duplicates, and the order of the versions isnot significant.

    Note

    All of the files listed in thefiles key MUST be associated with one of theversions in theversions key. Theversions key MAY contain versions withno associated files (to represent versions with no files uploaded, if the serverhas such a concept).

    Note

    Because servers may hold “legacy” data from before the adoption ofthe version specifiers specification (VSS), versionstrings currently cannot be required to be valid VSS versions, and thereforecannot be assumed to be orderable using the VSS rules. However, serversSHOULDuse normalized VSS versions where possible.

    Note

    Theversions key was added with API version 1.1.

Each individual file dictionary has the following keys:

  • filename: The filename that is being represented.

  • url: The URL that the file can be fetched from.

  • hashes: A dictionary mapping a hash name to a hex encoded digest of the file.Multiple hashes can be included, and it is up to the client to decide what to dowith multiple hashes (it may validate all of them or a subset of them, or nothingat all). These hash namesSHOULD always be normalized to be lowercase.

    Thehashes dictionaryMUST be present, even if no hashes are availablefor the file, however it isHIGHLY recommended that at least one secure,guaranteed-to-be-available hash is always included.

    By default, any hash algorithm available viahashlib (specifically any that canbe passed tohashlib.new() and do not require additional parameters) canbe used as a key for the hashes dictionary. At least one secure algorithm fromhashlib.algorithms_guaranteedSHOULD always be included. At the timeof this spec,sha256 specifically is recommended.

  • requires-python: Anoptional key that exposes theRequires-Pythonmetadata field. Where this is present, installer toolsSHOULD ignore the download when installing to a Python version thatdoesn’t satisfy the requirement.

    Unlikedata-requires-python inthe base HTML API specification, therequires-python key does notrequire any special escaping other than anything JSON does naturally.

  • core-metadata: Anoptional key that indicatesthat metadata for this file is available, via the same location as specified inthe API metadata file specification ({file_url}.metadata). Where thisis present, itMUST beeither a boolean to indicate if the file has an associated metadata file, or adictionary mapping hash names to a hex encoded digest of the metadata’s hash.

    When this is a dictionary of hashes instead of a boolean, then all the samerequirements and recommendations as thehashes key hold true for this key aswell.

    If this key is missing then the metadata file may or may not exist. If the keyvalue is truthy, then the metadata file is present, and if it is falsey then itis not.

    It is recommended that servers make the hashes of the metadata file available ifpossible.

  • dist-info-metadata: Anoptional, deprecated alias forcore-metadata.

    Index clientsMAY consume this key if present, as a legacy fallbackforcore-metadata.

    Important

    dist-info-metadata was standardized withPEP 658 and renamed tocore-metadata withPEP 714.

  • gpg-sig: Anoptional key that acts a boolean to indicate if the file hasan associated GPG signature or not. The URL for the signature file follows whatis specified inthe base HTML API specification ({file_url}.asc). If this key does not exist, thenthe signature may or may not exist.

  • yanked: Anoptional key which may be either a boolean to indicate if thefile has been yanked, or a non empty, but otherwise arbitrary, string to indicatethat a file has been yanked with a specific reason. If theyanked key is presentand is a truthy value, then itSHOULD be interpreted as indicating that thefile pointed to by theurl field has been “Yanked”.

    Note

    The semantics of how tools should handle yanked files isdescribed inFile Yanking.

  • size: Amandatory key. ItMUST contain an integer which is the file size in bytes.

    Note

    Thesize key was added with API version 1.1.

  • upload-time: Anoptional key that, if present,MUST contain a validISO 8601 date/time string in the formatyyyy-mm-ddThh:mm:ss.ffffffZwhich represents the time the file was uploaded to the index.

    As indicated by theZ suffix, the upload timeMUST use the UTC timezone.The fractional seconds part of the timestamp (the.ffffff part) is optional,and if present may contain up to 6 digits of precision. If a server does not recordupload time information for a file, itMAY omit theupload-time key.

    Note

    Theupload-time key was added with API version 1.1.

  • provenance: Anoptional key which, if presentMUST be either a JSONstring ornull. If notnull, itMUST be a URL to the file’sassociated provenance, with the same rules asdata-provenance in thebase HTML API specification.

    Note

    Theprovenance field was added with API version 1.3.

As an example:

{"meta":{"api-version":"1.4","project-status":"active","project-status-reason":"this project is not yet haunted"},"name":"holygrail","files":[{"filename":"holygrail-1.0.tar.gz","url":"https://example.com/files/holygrail-1.0.tar.gz","hashes":{"sha256":"...","blake2b":"..."},"requires-python":">=3.7","yanked":"Had a vulnerability","size":123456},{"filename":"holygrail-1.0-py3-none-any.whl","url":"https://example.com/files/holygrail-1.0-py3-none-any.whl","hashes":{"sha256":"...","blake2b":"..."},"requires-python":">=3.7","dist-info-metadata":true,"provenance":"https://example.com/files/holygrail-1.0-py3-none-any.whl.provenance","size":1337}],"versions":["1.0"]}

Note

While thefiles key is an array, and thus is required to be in some kindof an order, neitherthe base HTML API specification nor this spec requires any specific ordering northat the ordering is consistent from one request to the next. Mentally this isbest thought of as a set, but both JSON and HTML lack the functionality to havesets.

Content-Types

This spec proposes that all responses from the Simple API will have a standardcontent type that describes what the response is (a Simple API response), whatversion of the API it represents, and what serialization format has been used.

The structure of this content type will be:

application/vnd.pypi.simple.$version+format

Since only major versions should be disruptive to clients attempting tounderstand one of these API responses, only the major version will be includedin the content type, and will be prefixed with av to clarify that it is aversion number.

Which means that for the existing 1.0 API, the content types would be:

  • JSON:application/vnd.pypi.simple.v1+json

  • HTML:application/vnd.pypi.simple.v1+html

In addition to the above, a special “meta” version is supported namedlatest,whose purpose is to allow clients to request the absolute latest version, withouthaving to know ahead of time what that version is. It is recommended however,that clients be explicit about what versions they support.

To support existing clients which expect the existingthe base HTML APIspecification API responses touse thetext/html content type, this spec further definestext/html as an aliasfor theapplication/vnd.pypi.simple.v1+html content type.

Version + Format Selection

Now that there is multiple possible serializations, we need a mechanism to allowclients to indicate what serialization formats they’re able to understand. Inaddition, it would be beneficial if any possible new major version to the API canbe added without disrupting existing clients expecting the previous API version.

To enable this, this spec standardizes on the use of HTTP’sServer-Driven Content Negotiation.

While this spec won’t fully describe the entirety of server-driven contentnegotiation, the flow is roughly:

  1. The client makes an HTTP request containing anAccept header listing allof the version+format content types that they are able to understand.

  2. The server inspects that header, selects one of the listed content types,then returns a response using that content type (treating the absence ofanAccept header asAccept:*/*).

  3. If the server does not support any of the content types in theAcceptheader then they are able to choose between 3 different options for how torespond:

    1. Select a default content type other than what the client has requestedand return a response with that.

    2. Return a HTTP406NotAcceptable response to indicate that none ofthe requested content types were available, and the server was unableor unwilling to select a default content type to respond with.

    3. Return a HTTP300MultipleChoices response that contains a list ofall of the possible responses that could have been chosen.

  4. The client interprets the response, handling the different types of responsesthat the server may have responded with.

This spec does not specify which choices the server makes in regards to handlinga content type that it isn’t able to return, and clientsSHOULD be preparedto handle all of the possible responses in whatever way makes the most sense forthat client.

However, as there is no standard format for how a300MultipleChoicesresponse can be interpreted, this spec highly discourages servers from utilizingthat option, as clients will have no way to understand and select a differentcontent-type to request. In addition, it’s unlikely that the clientcouldunderstand a different content type anyways, so at best this response wouldlikely just be treated the same as a406NotAcceptable error.

This specdoes require that if the meta versionlatest is being used, theserverMUST respond with the content type for the actual version that iscontained in the response(i.e. anAccept:application/vnd.pypi.simple.latest+json request that returnsav1.x response should have aContent-Type ofapplication/vnd.pypi.simple.v1+json).

TheAccept header is a comma separated list of content types that the clientunderstands and is able to process. It supports three different formats for eachcontent type that is being requested:

  • $type/$subtype

  • $type/*

  • */*

For the use of selecting a version+format, the most useful of these is$type/$subtype, as that is the only way to actually specify the versionand format you want.

The order of the content types listed in theAccept header does not have anyspecific meaning, and the serverSHOULD consider all of them to be equallyvalid to respond with. If a client wishes to specify that they prefer a specificcontent type over another, they may use theAccept header’squality valuesyntax.

This allows a client to specify a priority for a specific entry in theirAccept header, by appending a;q= followed by a value between0 and1 inclusive, with up to 3 decimal digits. When interpreting this value,an entry with a higher quality has priority over an entry with a lower quality,and any entry without a quality present will default to a quality of1.

However, clients should keep in mind that a server is free to selectany ofthe content types they’ve asked for, regardless of their requested priority, andit may even return a content type that they didnot ask for.

To aid clients in determining the content type of the response that they havereceived from an API request, this spec requires that servers always include aContent-Type header indicating the content type of the response. This istechnically a backwards incompatible change, however in practicepip has been enforcing this requirementso the risks for actual breakages is low.

An example of how a client can operate would look like:

importemail.messageimportrequestsdefparse_content_type(header:str)->str:m=email.message.Message()m["content-type"]=headerreturnm.get_content_type()# Construct our list of acceptable content types, we want to prefer# that we get a v1 response serialized using JSON, however we also# can support a v1 response serialized using HTML. For compatibility# we also request text/html, but we prefer it least of all since we# don't know if it's actually a Simple API response, or just some# random HTML page that we've gotten due to a misconfiguration.CONTENT_TYPES=["application/vnd.pypi.simple.v1+json","application/vnd.pypi.simple.v1+html;q=0.2","text/html;q=0.01",# For legacy compatibility]ACCEPT=", ".join(CONTENT_TYPES)# Actually make our request to the API, requesting all of the content# types that we find acceptable, and letting the server select one of# them out of the list.resp=requests.get("https://pypi.org/simple/",headers={"Accept":ACCEPT})# If the server does not support any of the content types you requested,# AND it has chosen to return a HTTP 406 error instead of a default# response then this will raise an exception for the 406 error.resp.raise_for_status()# Determine what kind of response we've gotten to ensure that it is one# that we can support, and if it is, dispatch to a function that will# understand how to interpret that particular version+serialization. If# we don't understand the content type we've gotten, then we'll raise# an exception.content_type=parse_content_type(resp.headers.get("content-type",""))matchcontent_type:case"application/vnd.pypi.simple.v1+json":handle_v1_json(resp)case"application/vnd.pypi.simple.v1+html"|"text/html":handle_v1_html(resp)case_:raiseException(f"Unknown content type:{content_type}")

If a client wishes to only support HTML or only support JSON, then they wouldjust remove the content types that they do not want from theAccept header,and turn receiving them into an error.

Alternative Negotiation Mechanisms

While using HTTP’s Content negotiation is considered the standard way for a clientand server to coordinate to ensure that the client is getting an HTTP response thatit is able to understand, there are situations where that mechanism may not besufficient. For those cases this spec has alternative negotiation mechanisms thatmayoptionally be used instead.

URL Parameter

Servers that implement the Simple API may choose to support a URL parameter namedformat to allow the clients to request a specific version of the URL.

The value of theformat parameter should beone of the valid content types.Passing multiple content types, wild cards, quality values, etc… isnotsupported.

Supporting this parameter is optional, and clientsSHOULD NOT rely on it forinteracting with the API. This negotiation mechanism is intended to allow for easierhuman based exploration of the API within a browser, or to allow documentation ornotes to link to a specific version+format.

Servers that do not support this parameter may choose to return an error when it ispresent, or they may simple ignore its presence.

When a server does implement this parameter, itSHOULD take precedence over anyvalues in the client’sAccept header, and if the server does not support therequested format, it may choose to fall back to theAccept header, or choose anyof the error conditions that standard server-driven content negotiation typicallyhas (e.g.406NotAvailable,303MultipleChoices, or selecting a defaulttype to return).

Endpoint Configuration

This option technically is not a special option at all, it is just a naturalconsequence of using content negotiation and allowing servers to select which of theavailable content types is their default.

If a server is unwilling or unable to implement the server-driven content negotiation,and would instead rather require users to explicitly configure their client to selectthe version they want, then that is a supported configuration.

To enable this, a server should make multiple endpoints (for instance,/simple/v1+html/ and/or/simple/v1+json/) for each version+format that theywish to support. Under that endpoint, they can host a copy of their repository thatonly supports one (or a subset) of the content-types. When a client makes a requestusing theAccept header, the server can ignore it and return the content typethat corresponds to that endpoint.

For clients that wish to require specific configuration, they can keep track ofwhich version+format a specific repository URL was configured for, and when makinga request to that server, emit anAccept header thatonly includes the correctcontent type.

Recommendations

This section is non-normative, and represents what the spec authors believe to bethe best default implementation decisions for something implementing this spec, butit doesnot represent any sort of requirement to match these decisions.

These decisions have been chosen to maximize the number of requests that can bemoved onto the newest version of an API, while maintaining the greatest amountof compatibility. In addition, they’ve also tried to make using the API provideguardrails that attempt to push clients into making the best choices it can.

It is recommended that servers:

  • Support all 3 content types described in this spec, using server-drivencontent negotiation, for as long as they reasonably can, or at least aslong as they’re receiving non trivial traffic that uses the HTML responses.

  • When encountering anAccept header that does not contain any content typesthat it knows how to work with, the server should not ever return a300MultipleChoice response, and instead return a406NotAcceptableresponse.

    • However, if choosing to use the endpoint configuration, you should prefer toreturn a200OK response in the expected content type for that endpoint.

  • When selecting an acceptable version, the server should choose the highest versionthat the client supports, with the most expressive/featureful serialization format,taking into account the specificity of the client requests as well as anyquality priority values they have expressed, and it should only use thetext/html content type as a last resort.

It is recommended that clients:

  • Support all 3 content types described in this spec, using server-drivencontent negotiation, for as long as they reasonably can.

  • When constructing anAccept header, include all of the content typesthat you support.

    You should generallynot include a quality priority value for your contenttypes, unless you have implementation specific reasons that you want theserver to take into account (for example, if you’re using the standard libraryHTML parser and you’re worried that there may be some kinds of HTML responsesthat you’re unable to parse in some edge cases).

    The one exception to this recommendation is that it is recommended that youshould include a;q=0.01 value on the legacytext/html content type,unless it is the only content type that you are requesting.

  • Explicitly select what versions they are looking for, rather than using thelatest meta version during normal operation.

  • Check theContent-Type of the response and ensure it matches somethingthat you were expecting.

History

  • September 2015: initial form of the HTML format, inPEP 503

  • July 2016: Requires-Python metadata, in an update toPEP 503

  • May 2019: “yank” support, inPEP 592

  • July 2020: API versioning convention and metadata, and declaring the HTMLformat as API v1, inPEP 629

  • May 2021: providing package metadata independently from a package, inPEP 658

  • May 2022: initial form of the JSON format, with a mechanism for clients tochoose between them, and declaring both formats as API v1, inPEP 691

  • October 2022: project versions and file size and upload-time in the JSONformat, inPEP 700

  • June 2023: renaming the field which provides package metadata independentlyfrom a package, inPEP 714

  • November 2024: provenance metadata in the HTML and JSON formats, inPEP 740

  • July 2025: project status markers in the HTML and JSON formats, inPEP 792

  • July 2025: layout changes (dedicated page for file yanking, introduce concepts before API details)

On this page

[8]ページ先頭

©2009-2025 Movatter.jp