Tutorial 7: Schemas & client libraries

转载自:http://www.django-rest-framework.org/tutorial/7-schemas-and-client-libraries/

Tutorial 7: Schemas & client libraries

A schema is a machine-readable document that describes the available API endpoints, their URLS, and what operations they support.

Schemas can be a useful tool for auto-generated documentation, and can also be used to drive dynamic client libraries that can interact with the API.

Core API

In order to provide schema support REST framework uses Core API.

Core API is a document specification for describing APIs. It is used to provide an internal representation format of the available endpoints and possible interactions that an API exposes. It can either be used server-side, or client-side.

When used server-side, Core API allows an API to support rendering to a wide range of schema or hypermedia formats.

When used client-side, Core API allows for dynamically driven client libraries that can interact with any API that exposes a supported schema or hypermedia format.

Adding a schema

REST framework supports either explicitly defined schema views, or automatically generated schemas. Since we‘re using viewsets and routers, we can simply use the automatic schema generation.

You‘ll need to install the coreapi python package in order to include an API schema.

$ pip install coreapi

We can now include a schema for our API, by including an autogenerated schema view in our URL configuration.

from rest_framework.schemas import get_schema_view

schema_view = get_schema_view(title=‘Pastebin API‘)

urlpatterns = [
    url(r‘^schema/$‘, schema_view),
    ...
]

If you visit the API root endpoint in a browser you should now see corejson representation become available as an option.

We can also request the schema from the command line, by specifying the desired content type in the Accept header.

$ http http://127.0.0.1:8000/schema/ Accept:application/coreapi+json
HTTP/1.0 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/coreapi+json

{
    "_meta": {
        "title": "Pastebin API"
    },
    "_type": "document",
    ...

The default output style is to use the Core JSON encoding.

Other schema formats, such as Open API (formerly Swagger) are also supported.

Using a command line client

Now that our API is exposing a schema endpoint, we can use a dynamic client library to interact with the API. To demonstrate this, let‘s use the Core API command line client.

The command line client is available as the coreapi-cli package:

$ pip install coreapi-cli

Now check that it is available on the command line...

$ coreapi
Usage: coreapi [OPTIONS] COMMAND [ARGS]...

  Command line client for interacting with CoreAPI services.

  Visit http://www.coreapi.org for more information.

Options:
  --version  Display the package version number.
  --help     Show this message and exit.

Commands:
...

First we‘ll load the API schema using the command line client.

$ coreapi get http://127.0.0.1:8000/schema/
<Pastebin API "http://127.0.0.1:8000/schema/">
    snippets: {
        highlight(id)
        list()
        read(id)
    }
    users: {
        list()
        read(id)
    }

We haven‘t authenticated yet, so right now we‘re only able to see the read only endpoints, in line with how we‘ve set up the permissions on the API.

Let‘s try listing the existing snippets, using the command line client:

$ coreapi action snippets list
[
    {
        "url": "http://127.0.0.1:8000/snippets/1/",
        "id": 1,
        "highlight": "http://127.0.0.1:8000/snippets/1/highlight/",
        "owner": "lucy",
        "title": "Example",
        "code": "print(‘hello, world!‘)",
        "linenos": true,
        "language": "python",
        "style": "friendly"
    },
    ...

Some of the API endpoints require named parameters. For example, to get back the highlight HTML for a particular snippet we need to provide an id.

$ coreapi action snippets highlight --param id=1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
<head>
  <title>Example</title>
  ...

Authenticating our client

If we want to be able to create, edit and delete snippets, we‘ll need to authenticate as a valid user. In this case we‘ll just use basic auth.

Make sure to replace the <username> and <password> below with your actual username and password.

$ coreapi credentials add 127.0.0.1 <username>:<password> --auth basic
Added credentials
127.0.0.1 "Basic <...>"

Now if we fetch the schema again, we should be able to see the full set of available interactions.

$ coreapi reload
Pastebin API "http://127.0.0.1:8000/schema/">
    snippets: {
        create(code, [title], [linenos], [language], [style])
        delete(id)
        highlight(id)
        list()
        partial_update(id, [title], [code], [linenos], [language], [style])
        read(id)
        update(id, code, [title], [linenos], [language], [style])
    }
    users: {
        list()
        read(id)
    }

We‘re now able to interact with these endpoints. For example, to create a new snippet:

$ coreapi action snippets create --param title="Example" --param code="print(‘hello, world‘)"
{
    "url": "http://127.0.0.1:8000/snippets/7/",
    "id": 7,
    "highlight": "http://127.0.0.1:8000/snippets/7/highlight/",
    "owner": "lucy",
    "title": "Example",
    "code": "print(‘hello, world‘)",
    "linenos": false,
    "language": "python",
    "style": "friendly"
}

And to delete a snippet:

$ coreapi action snippets delete --param id=7

As well as the command line client, developers can also interact with your API using client libraries. The Python client library is the first of these to be available, and a Javascript client library is planned to be released soon.

For more details on customizing schema generation and using Core API client libraries you‘ll need to refer to the full documentation.

Reviewing our work

With an incredibly small amount of code, we‘ve now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.

We‘ve walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.

You can review the final tutorial code on GitHub, or try out a live example in the sandbox.

Onwards and upwards

We‘ve reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:

Now go build awesome things.

时间: 2024-11-03 01:11:31

Tutorial 7: Schemas & client libraries的相关文章

API(七)之Schemas &amp; client libraries

模式是一种机器可读的文档,用于描述可用的API端点,其URLS以及它们支持的操作. 模式可以是自动生成文档的有用工具,也可以用于驱动可以与API进行交互的动态客户端库. Core API 为了提供支持REST框架的schema而使用Core API. Core API是用于描述API的文档规范.它用于提供可用端点的内部表现格式以及API暴露的可能的交互.它可以用于服务器端或客户端. 当使用服务器端时,Core API允许API支持各种模式或超媒体格式的渲染. When used client-s

编译pure-ftpd时提示错误Your MySQL client libraries aren&#39;t properly installed

如果出现类似configure: error: Your MySQL client libraries aren’t properly installed 的错误,请将mysql目录下的 include/mysql下的mysql.h文件以及lib/mysql下的全部文件,连接(直接复制过去或许也可)到 /usr/lib 目录下(参考) cp /www/wdlinux/mysql-5.5.x/include/mysql/mysql.h /usr/lib/ cp /www/wdlinux/mysql

This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed(在64位模式下运行安装了32位的Oracle客户端组件时,会发生此问题)

部署win服务时出现下面的问题: 在事件查看器中看到如下错误: 日志名称: Application来源: ***调度服务日期: 2014/5/21 12:53:21事件 ID: 0任务类别: 无级别: 错误关键字: 经典用户: 暂缺计算机: ams-webserver描述:Service cannot be started. Achievo.Utility.DataAccess.DbException: Attempt to load Oracle client libraries threw

Calling a Web API From a .NET Client (C#)

by Mike Wasson+ Download Completed Project This tutorial shows how to call a web API from a .NET application, using System.Net.Http.HttpClient.+ In this tutorial, we will write an client application that consumes the following web API.+ Action HTTP m

Intro to Jedis – the Java Redis Client Library

转自:http://www.baeldung.com/jedis-java-redis-client-library 1. Overview This article is an introduction to Jedis, a client library in Java for Redis – the popular in-memory data structure store that can persist on disk as well. It is driven by a keyst

Instant Buy Android API Tutorial

转自:https://developers.google.com/wallet/instant-buy/android/tutorial This tutorial guides you through integrating Instant Buy into a purchase flow, in the context of an example bike store. The tutorial provides details and complete source code to hel

Why GraphQL is Taking Over APIs

A few years ago, I managed a team at DocuSign that was tasked with re-writing the main DocuSign web app which was used by tens of millions of users. The APIs didn’t exist yet to support our new shiny front-end app because since the beginning the web

OData

http://scn.sap.com/docs/DOC-44986 Introduction OData services provide a uniform interface for interacting with their resources, and in addition are self-describing: The service document (located at the service root) lists the available top-level reso

【ASP.NET Web API教程】3.3 通过WPF应用程序调用Web API(C#)

参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/core-static-files.html http://www.yuanjiaocheng.net/ASPNET-CORE/setup-mvc.html http://www.yuanjiaocheng.net/ASPNET-CORE/mvc-design-pattern.html http://www.yuanjiaocheng.net/ASPNET-CORE/mvc-routing.html h