harbor rest api 转graphql api

本文介绍如何通过swagger-to-graphql及graphql-binding-openapi等工具将RESTful API转换为GraphQL API,涵盖模型生成、CLI工具使用及认证处理等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理

实际上就是使用graphql 中的binding,首先基于swagger api 进行schema 生成,后边就是
使用binding 进行graphql 请求api 转换为rest api 请求,目前测试过两个开源的方案:
prisma 的graphql-openapi-binding 以及swagger-graphql 类库

步骤

  • swagger 模型生成graphql schema

使用cli 工具 swagger-to-graphql

npm install -g swagger-to-graphql 
harbor swagger 文件
https://raw.githubusercontent.com/goharbor/harbor/master/docs/swagger.yaml
可以使用swagger editor 转换为json格式,同时我们暂时需要先删除带有文件操作的api
swagger-to-graphql --swagger=/path/to/swaggerjson > ./swagger.graphql
  • swagger-to-graphql 使用

    比较简单,基于swagger 2 graphql npm 包

package.json:
{
"name": "swagger-graphql",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"babel-polyfill": "^6.26.0",
"express": "^4.16.3",
"express-graphql": "^0.6.12",
"graphql": "^0.13.2",
"swagger-to-graphql": "^1.4.0"
},
"scripts": {
"start": "node app"
}
}

app.js:
require('babel-polyfill');
const express = require('express');
const app = express();
const graphqlHTTP = require('express-graphql');
const graphQLSchema = require('swagger-to-graphql');

const proxyUrl = 'https://harborserver/api';
const pathToSwaggerSchema = `${__dirname}/api/swagger.json`;
const customHeaders = {
Authorization: 'Basic YWRkOmJhc2ljQXV0aA=='
};

graphQLSchema(pathToSwaggerSchema, proxyUrl, customHeaders).then(schema => {
app.use('/graphql', graphqlHTTP(() => {
return {
schema,
graphiql: true
};
}));

app.listen(3009, '0.0.0.0', () => {
console.info('http://localhost:3009/graphql');
});
}).catch(e => {
console.log(e);
});
  • graphql-binding-openapi

    类似,只是步骤多了几步

app.js

const { OpenApi } = require('graphql-binding-openapi')
const { GraphQLServer } = require('graphql-yoga')
const {importSchema} = require("graphql-import")

const typeDefs = importSchema("./schema.graphql")
const resolvers = {
Query: {
get_search: async (parent, args, context, info) => {
return context.harbor.query.get_search({ status: "available" }, context, info)
}
}
}

const server = new GraphQLServer({
resolvers,
typeDefs,
context: async req => ({
...req,
harbor: await OpenApi.init('./harbor.json', 'https://harborapiserver')
})
});

server.start(() => console.log('Server running on http://localhost:4000'))

package.json:

{
"name": "open-api",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"graphql-binding-openapi": "^1.0.5",
"graphql-import": "^0.6.0",
"graphql-yoga": "^1.16.0"
},
"scripts": {
"start":"node app"
}
}

几个问题

  • file schema type
因为字段类型file 暂时转换不支持,但是可以手工调整
转换的时候会提示file 类型未定义,解决方法,暂时删除了关于文件的部分
实际上可以集成prisma 后者apollo 自带file type 的resolver
  • 访问api 登录的问题
当前测试的开放的api,大部分api是需要进行认证的,可以还有待测试
实际上当前支持basic 认证可以使用 https://username:password@harborserver/api
或者使用 Authorization: "Basic 用户名和密码的base64加密字符串" 的请求

效果

测试

  • query
query {
  get_repositories_top(count:3){
    name
    description
    pull_count
  } 
}
  • 结果
{
  "data": {
    "get_repositories_top": [
      {
        "name": "library/kubedns-amd64",
        "description": null,
        "pull_count": null
      },
      {
        "name": "coredns/coredns",
        "description": null,
        "pull_count": null
      },
      {
        "name": "marketing/mk-platform-order-test",
        "description": null,
        "pull_count": null
      }
    ]
  }
}
  • 界面

参考资料

https://github.com/graphql-binding/graphql-binding-openapi
https://github.com/yarax/swagger-to-graphql#readme
https://github.com/rongfengliang/swagger-to-graphql-docker/tree/harborgraphql

 
 
 
 
### Harbor与Java API交互 Harbor作为企业级容器镜像仓库,支持多种编程语言与其API进行交互。对于Java开发者而言,可以通过调用RESTful风格的HTTP接口来实现对Harbor的操作。 #### 准备工作 为了能够顺利地使用Java代码访问Harbor服务端口,默认情况下为`https://<harbor-server>:443/api/v2.0/...`,需要先完成如下准备工作: - 获取管理员账号或具有相应权限用户的用户名密码; - 如果启用了HTTPS,则需确认客户端信任服务器证书;如果采用自签名SSL/TLS证书,在发起请求前应设置忽略SSL验证逻辑[^1]。 #### Maven依赖引入 为了让项目具备发送HTTP请求的能力,推荐添加Apache HttpClient库的支持。可以在项目的pom.xml文件中加入以下依赖项: ```xml <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 --> <dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.1</version> </dependency> <!-- JSON解析工具 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> </dependency> ``` #### 登录获取Token 由于Harbor的安全机制要求每次请求都携带有效的认证信息,因此首先要执行登录动作并保存返回的身份令牌(token)。下面给出了一段简单的示例代码展示如何利用Basic Auth方式向Harbor提交凭证从而获得JWT token: ```java import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.io.entity.EntityUtils; public class LoginExample { public static void main(String[] args) throws Exception{ String url = "https://your-harbor-domain/service/token"; CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost post = new HttpPost(url); // 设置header参数 post.setHeader("Content-Type", "application/json"); post.addHeader("Authorization","Basic "+ Base64.getEncoder().encodeToString(("admin:password").getBytes())); // 发送post请求 CloseableHttpResponse response = client.execute(post); System.out.println(EntityUtils.toString(response.getEntity())); } finally { client.close(); } } } ``` 请注意替换上述代码中的`your-harbor-domain`, `admin`, 和 `password`字段为你自己的实际值。这段程序会打印出由Harbor颁发给合法用户的JSON Web Token (JWT),后续其他API调用都需要带上这个token作为身份证明。 #### 查询项目列表 一旦成功获得了token之后就可以开始查询数据了。这里提供了一个例子说明怎样读取所有的project对象: ```java // 假设已经得到了之前提到的有效token字符串变量名为accessToken String getUrl = "https://your-harbor-domain/api/v2.0/projects"; CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom() .setConnectTimeout(5000).build()) .build(); HttpGet httpGet = new HttpGet(getUrl); httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken ); try(CloseableHttpResponse httpResponse = httpClient.execute(httpGet)){ int statusCode = httpResponse.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK){ String resultJsonStr = EntityUtils.toString(httpResponse.getEntity()); ObjectMapper mapper = new ObjectMapper(); List<ProjectDTO> projectsList = Arrays.asList(mapper.readValue(resultJsonStr , ProjectDTO[].class)); for(ProjectDTO p :projectsList ){ System.out.printf("%s\n",p.getName()); } } } catch(Exception e){ logger.error(e.getMessage(),e); } static class ProjectDTO{ // DTO类定义省略... } ``` 以上就是基于Java应用程序连接到Harbor实例的一些基本指导。当然还有更多高级功能等待探索,比如上传下载image、管理成员角色分配等等。具体细节可以参阅官方文档了解更全面的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值