"Try it out" does not work in springdoc-openapi-ui? - springdoc-openapi-ui

I use springdoc-openapi-ui:1.6.9 to generate documentation, and I have this controller:
#Operation(summary = "Get a file meta by its ID")
#ApiResponses({
#ApiResponse(responseCode = "200", content = {
#Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = #Schema(implementation = FileMetaResponse.class))
}),
#ApiResponse(responseCode = "404", description = "Not found", content = {
#Content(mediaType = MediaType.TEXT_PLAIN_VALUE,
schema = #Schema(implementation = String.class))
})
})
#RequestMapping(value = "/files/meta", method = RequestMethod.GET)
public ResponseEntity<Object> getFileMate(#RequestParam final #NotEmpty String id) {
OssFile ossFIle = fileService.findFileById(UUID.fromString(id));
if (ossFIle == null) {
return new ResponseEntity<>("File not found", HttpStatus.NOT_FOUND);
}
FileMetaResponse body = new FileMetaResponse();
BeanUtils.copyProperties(ossFIle, body);
return new ResponseEntity<>(body, HttpStatus.OK);
}
But, I always got code 200 and no response body When I execute a request to this API with any id. By debugging code, I found that this request didn't arrive to backend. ui shows:
enter image description here
However, it works normally when I delete response mediatype definition, as follows:
/**
* Get a file meta by given a file ID.
*
* #param id file uuid
* #return a found OssFile meta if successful
*/
#Operation(summary = "Get a file meta by its ID")
#ApiResponses({
#ApiResponse(responseCode = "200", content = {
#Content(
schema = #Schema(implementation = FileMetaResponse.class))
}),
#ApiResponse(responseCode = "404", description = "Not found", content = {
#Content(
schema = #Schema(implementation = String.class))
})
})
#RequestMapping(value = "/files/meta", method = RequestMethod.GET)
public ResponseEntity<Object> getFileMate(#RequestParam final #NotEmpty String id) {
OssFile ossFIle = fileService.findFileById(UUID.fromString(id));
if (ossFIle == null) {
return new ResponseEntity<>("File not found", HttpStatus.NOT_FOUND);
}
FileMetaResponse body = new FileMetaResponse();
BeanUtils.copyProperties(ossFIle, body);
return new ResponseEntity<>(body, HttpStatus.OK);
}
By comparing the two requests, the Accept field of request header is different: the accept is application/json when media type is defined, otherwise the accept is */*.
If I want to define response media type and execute request on swagger-ui web, How should I do?

Related

NOT NULL constraint failed: accounts_personalcolor.user_id

I am new to Django and have trouble making django-rest-framework API for post, inheriting APIView. I'm using a serializer, that inherits djangos ModelSerializer. I face NOT NULL constraint failed: accounts_personalcolor.user_id error whenever I try saving the serializer or model object.
color.js posts image using Django rest framework as follows.
function PersonalColorScreen({navigation,route}) {
const {image} = route.params;
console.log('uri is', image.uri);
const [userToken, setUserToken] = React.useState(route.params?.userToken);
const requestHeaders = {
headers: {
"Content-Type": "multipart/form-data"
}
}
// helper function: generate a new file from base64 String
//convert base64 image data to file object to pass it onto imagefield of serializer.
//otherwise, serializer outputs 500 Internal server error code
const dataURLtoFile = (dataurl, filename) => {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n) {
u8arr[n - 1] = bstr.charCodeAt(n - 1)
n -= 1 // to make eslint happy
}
return new File([u8arr], filename, { type: mime })
}
//random number between 0-9
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
// generate file from base64 string
const file = dataURLtoFile(image.uri, `${getRandomInt(10)}.png`)
const formData= new FormData();
formData.append('img',file,file.name);
console.log(file.name);
//axios post request to send data
// axios.post('http://localhost:8000/accounts/personalcolor/', formData,requestHeaders)
//multipartparser
axios.post('http://localhost:8000/accounts/personalcolor/', formData, requestHeaders)
.then(res => {
console.log(res);
if (res.data === 'upload another image') {
setimageError('upload another image');
} else {
// signUp(userToken);
let color;
switch (res.data){
case ('spring'):
color = 'spring';
break;
case ('summer'):
color = 'summer';
break;
case ('fall'):
color = 'fall';
break;
case ('winter'):
color = 'winter';
break;
}
}
})
.catch(err => {
console.error(err.response.data)
})
view.py handles the image posted. I tried #1 but it did not work. So I tried #2, or #3 instead and they return the same error saying NOT NULL constraint failed: accounts_personalcolor.user_id. I thought saving the serializer or model object creates id(Autofield)automatically and I don't understand why I face this error.
views.py
#api_view(['POST'])
def personalcolor(request):
# 1
image=request.FILES['img']
personal_color=Personalcolor()
personal_color.img=image
personal_color.save()
# 2
image=request.FILES['img']
personal_color=Personalcolor.objects.create(img=image)
personal_color.save()
# 3
serializer = ColorSerializer(data=request.data)
# validation of input data
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
model.py
class Personalcolor(models.Model):
objects = models.Manager()
img = models.ImageField('personal_img',upload_to="personalcolor/", blank=True)
serializer.py
class ColorSerializer(serializers.ModelSerializer):
class Meta:
model = Personalcolor
fields = ['img']
As mentioned above, executing the code returns django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_personalcolor.user_id. Any help would be greatly appreciated.
Set null to true in your img field like:
img = models.ImageField('personal_img',upload_to="personalcolor/", blank=True, null=True)
Then in your migrations folder within the app where the Personalcolor model is located, delete all of the files that look like 000*_initial.py
Then run makemigrations and migrate

Asp.net core file upload with Graphql-dotnet

I am trying to upload an image file with graphql-dotnet, but it is never successful.
I am taking file object in my GraphQLController:
var files = this.Request.Form.Files;
var executionOptions = new ExecutionOptions
{
Schema = _schema,
Query = queryToExecute,
Inputs = inputs,
UserContext = files,
OperationName = query.OperationName
};
And here my Mutation:
Field<UserGraphType>(
"uploadUserAvatar",
Description="Kullanıcı resmi yükleme.",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<IntGraphType>> { Name = "Id", Description = "Identity Alanı" }
),
resolve: context => {
var file = context.UserContext.As<IFormCollection>();
var model = userService.UploadAvatar(context.GetArgument<int>("Id"),file);
return true;
}
);
I think it is accepting the only JSON. It is not accepting the request as a file type.
Also I am using React & apollo-client at the client-side. It has an error in the console:
Failed to load http://localhost:5000/graphql: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am trying to send the query like this:
const { selectedFile,id } = this.state
this.props.uploadAvatar({
variables: {id},
file:selectedFile
}).then(result => {
console.log(result);
});
What can I do to achieve this?
Failed to load http://localhost:5000/graphql: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
This error means you need to enable CORS.
See these docs: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1
Essentially you need these two things:
services.AddCors();
app.UseCors(builder =>
builder.WithOrigins("http://example.com"));
I would also suggest to look at this Deserializer helper function in the GraphQL.Relay project. It helps your server handle a multipart/form-data request. You can then use the parsed query information and files and pass it to the DocumentExecutor.
https://github.com/graphql-dotnet/relay/blob/master/src/GraphQL.Relay/Http/Deserializer.cs
public static class Deserializer
{
public static async Task<RelayRequest> Deserialize(Stream body, string contentType)
{
RelayRequest queries;
switch (contentType)
{
case "multipart/form-data":
queries = DeserializeFormData(body);
break;
case "application/json":
var stream = new StreamReader(body);
queries = DeserializeJson(await stream.ReadToEndAsync());
break;
default:
throw new ArgumentOutOfRangeException($"Unknown media type: {contentType}. Cannot deserialize the Http request");
}
return queries;
}
private static RelayRequest DeserializeJson(string stringContent)
{
if (stringContent[0] == '[')
return new RelayRequest(
JsonConvert.DeserializeObject<RelayQuery[]>(stringContent),
isBatched: true
);
if (stringContent[0] == '{')
return new RelayRequest() {
JsonConvert.DeserializeObject<RelayQuery>(stringContent)
};
throw new Exception("Unrecognized request json. GraphQL queries requests should be a single object, or an array of objects");
}
private static RelayRequest DeserializeFormData(Stream body)
{
var form = new MultipartFormDataParser(body);
var req = new RelayRequest()
{
Files = form.Files.Select(f => new HttpFile {
ContentDisposition = f.ContentDisposition,
ContentType = f.ContentType,
Data = f.Data,
FileName = f.FileName,
Name = f.Name
})
};
req.Add(new RelayQuery {
Query = form.Parameters.Find(p => p.Name == "query").Data,
Variables = form.Parameters.Find(p => p.Name == "variables").Data.ToInputs(),
});
return req;
}
}

Web API 2, return string as a file

I have a Web API 2 POST endpoint which takes a parameter, queries the database and returns an xml string as the response.
public async Task<IHttpActionResult> Post(long groupId)
{
People people = await _someService.GetPeople(groupId);
XElement peopleXml = _xmlService.ConverToXml(people);
return Ok(peopleXml);
}
How do I to return the xml as a file instead?
Figured it out myself, but I hope there is a simpler way -
public async Task<IHttpActionResult> Post(long groupId)
{
People people = await _someService.GetPeople(groupId);
XElement peopleXml = _xmlService.ConverToXml(people);
byte[] toBytes = Encoding.Unicode.GetBytes(peopleXml.ToString());
var stream = new MemoryStream(toBytes);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.txt"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
var response = ResponseMessage(result);
return response;
}

AngularJs, how to set empty string in URL

In the controller I have below function:
#RequestMapping(value = "administrator/listAuthor/{authorName}/{pageNo}", method = { RequestMethod.GET,
RequestMethod.POST }, produces = "application/json")
public List<Author> listAuthors(#PathVariable(value = "authorName") String authorName,
#PathVariable(value = "pageNo") Integer pageNo) {
try {
if (authorName == null) {
authorName = "";
}
if (pageNo == null) {
pageNo = 1;
}
return adminService.listAuthor(authorName, pageNo);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This function fetches and returns data from mysql database based on "authorName" and "pageNo". For example, when "authorName = a" and "pageNo = 1" I have:
Data I get when "authorName = a" and "pageNo = 1"
Now I want to set "authorName" as ""(empty string), so that I can fetch all the data from mysql database (because the SQL statement "%+""+%" in backend will return all the data).
What can I do if I want to set authorName = empty string?
http://localhost:8080/spring/administrator/listAuthor/{empty string}/1
Thanks in advance!
I don't think that you can encode empty sting to url, what I suggest you to do is to declare some constant that will be your code to empty string - such as null.
Example:
administrator/listAuthor/null/90
Afterwards , on server side, check if authorName is null and set local parameter with empty stirng accordingly.

Swagger documentation for BeanParam

I'm trying to document one of my java APIs (implemented in Apache CXF) using Swagger, that receives it's parameters using a Bean Param. Something like:
#GET
#Produces({SemanticMediaType.JSON_LD, MediaType.APPLICATION_JSON_VALUE})
#ApiOperation(value = "Retrieves Themes", position = 0)
#ApiResponses(value = {#ApiResponse(code = 200,
message = "Retrieval was successful"), #ApiResponse(code = 403,
message = "Missing or invalid x-business-group-id header"), #ApiResponse(code = 500,
message = "Internal server error")})
public Response get(#QueryParam(URI_PARAM_NAME) String uri,
final #ApiParam #Valid #BeanParam ThemeParams themeParams) { ... }
I read that Swagger already implements support for BeanParams, but when I try to run it, in swagger-ui, I only see one parameter called "body" and a text field, nothing related to the contents of my BeanParam.
Can somebody provide some assistance with this?
This is a bit old, but for those who are having the same issues, here is what I found helped.
If you are using the DefaultJaxrsConfig, change it to JerseyJaxrsConfig.
If you are linking to swagger-jersey-jaxrs_..., change it to swagger-jersey2-jxsrs_...
You can refer to.
#POST
#Path("/users")
#ApiOperation(value = "vdc", position = 1, notes = "vdc")
#ApiResponses(value = {
#ApiResponse(code = 200, message = "OK",response=UserCreateResponse.class),
#ApiResponse(code = 30601, message = "'httpcode': 400 'Errormsg': Request Params Not Valid"),
#ApiResponse(code = 30602, message = "'httpcode':404 'Errormsg': Data Required Not Found"),
#ApiResponse(code = 30603, message = "'httpcode':405 'Errormsg': Method Not Allowed"),
#ApiResponse(code = 30604, message = "'httpcode':408 'Errormsg': Request Time Expires Timeout"),
#ApiResponse(code = 30605, message = "'httpcode':500 'Errormsg': Internal Server Error") })
public Response createUsersWithArrayInput(
#ApiParam(value = "ID", name = "platform_id", required = true) #QueryParam(value = "platform_id") String platformId,
#ApiParam(value="body",name="user",required=true)UserCreate userCreate) {}
UserCreate.java
#ApiModel("UserCreate")
public class UserCreate {
#ApiModelProperty(value="VDC Id",required=false)
#JsonStringSchema(optional=true,description="VDC Id")
private String vdcId;
#ApiModelProperty(value="description",required=true)
private String name;
#ApiModelProperty(value="description",required=false)
private String password;
}

Resources